File.ReadLines keeps file locked after reading it and i can't write into it - file

For some reason File.ReadLines keeps the file that im reading locked, and when i am trying to write text into it using a streamWriter, i get an error that it is being used by another process. If i don't read it first, writing into it works fine. Here is my code:
IEnumerable<String> lines;
private void loadCfg()
{
lines = File.ReadLines(Application.StartupPath + #"\server.cfg");
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}

Well you should read all the lines using StreamReader class that way your file will be properly closed I altered the way you are reading lines to read all lines using StreamReader try the following version
List<string> lines = new List<string>()
private void loadCfg()
{
string temp = null;
StreamReader rd = new StreamReader(Application.StartupPath + #"\server.cfg");
temp = rd.ReadLine();
while(temp != null)
{
lines.Add(temp);
temp = rd.ReadLine();
}
rd.Close();
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}
I have not tested the code but I am sure it will solve your problem

Related

How do I store an entire file into an array?

so I want to store the file I read into an array but I am not sure how to. I am trying to use an arraylist but when I compile it in the console I don't it is not the same as the text file
this is my code
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
String line = null;
ArrayList<String> list = new ArrayList<String>();
try {
fr = new FileReader("sample.txt");
br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
list.add(line);
line = br.readLine();
for(String s : list){
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
it looks to me like you're double advancing your position in the file by having line=br.readLine() both in your while condition and after adding to the ArrayList. Also, is there a reason that you're outputting the contents before you've processed the entire file instead of outside the while loop?

cannot find symbol ActionListener and try catch

I have a problem w my applet: shortly speaking, I want to "take" the variable curreny which is taken from xml and print it when I click on the button OK. The error I get is: error: cannot find symbol curreny. The problem is not importing variable from xml, because I checked separately if it works.
Sorry for the messy code, I'm new to java. All the neccessary packages are imported in the original source, but i didnt put it here just to make the code shorter. EDIT: I deleted part of the code consisting GUI to make it shorter, as you suggested.
public class App2 extends Applet implements ActionListener {
TextField T1 = new TextField();
Label L1 = new Label();
/* GUI code here */
public void actionPerformed(ActionEvent ae)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDocument = db.parse(new URL("http://www.nbp.pl/kursy/xml/LastA.xml").openStream());
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/tabela_kursow/pozycja[3]/kurs_sredni";
// System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
String kurs_dolara = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_dolara = Double.parseDouble(kurs_dolara.replace(',', '.'));
System.out.println(d_kurs_dolara*6);
}
expression = "/tabela_kursow/pozycja[8]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_euro = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_euro = Double.parseDouble(kurs_euro.replace(',', '.'));
System.out.println(d_kurs_euro*6);
}
expression = "/tabela_kursow/pozycja[11]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_funta = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_funta = Double.parseDouble(kurs_funta.replace(',', '.'));
System.out.println(d_kurs_funta*6);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
String wynik = String.valueOf(d_kurs_euro);
L1.setText(wynik);
repaint();
}}

Windows Phone 8 mp3 playing problems

I am trying to play mp3 in my wp 8 app, i think forgot something, can you please help
my simplified code is as it goes:
in page.xaml.cs code is:
public void Play(object sender, RoutedEventArgs e)
{
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
{
BackgroundAudioPlayer.Instance.Pause();
}
else
{
BackgroundAudioPlayer.Instance.Play();
}
}
in App.xaml.cs code is:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = new string[] { "song.mp3"};
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = "Sounds/" + _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
{
int chunkSize = 4096;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}
}
i can see that my BackgroundAudioPlayer.Instancestate never changes, but I can't figure out why (play function is trigered)
You need to tell the BackgroundAudioPlayer which track to play.
Something like:
var track = new AudioTrack(
new Uri("/song.mp3", UriKind.Relative),
"song name",
"artist name",
"album name",
null); // no artwork
BackgroundAudioPlayer.Instance.Track = track;
BackgroundAudioPlayer.Instance.Play();

Upload files with HTTPWebrequest from SilverLight application (Why does Content Length is 13?)

Friends!
Help me, please!
I try to post file from Silverlight. I use such class:
public class HttpHelper
{
public WebRequest Request { get; set; }
public Stream Filestream { get; private set; }
public HttpHelper(Stream filestream)
{
Request = WebRequest.Create("http://www.mysite.com/recieve");
Request.Method = "POST";
Request.ContentType = "application/octet-stream";
Filestream = filestream;
}
private static void BeginFilePostRequest(IAsyncResult ar)
{
HttpHelper helper = ar.AsyncState as HttpHelper;
if (helper != null)
{
byte[] bytes = new byte[helper.Filestream.Length];
int sf = helper.Filestream.Read(bytes, 0, (int)helper.Filestream.Length);
//helper.Request.ContentLength = bytes.Length; //It doesn't work in SL
using (StreamWriter writer = new StreamWriter(helper.Request.EndGetRequestStream(ar)))
{
writer.Write(bytes);
}
helper.Request.BeginGetResponse(new AsyncCallback(HttpHelper.BeginResponse), helper);
}
}
private static void BeginResponse(IAsyncResult ar)
{
HttpHelper helper = ar.AsyncState as HttpHelper;
if (helper != null)
{
HttpWebResponse response = (HttpWebResponse)helper.Request.EndGetResponse(ar);
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream))
{
//anything...
}
}
}
}
}
public void PostFile()
{
this.Request.BeginGetRequestStream(new AsyncCallback(HttpHelper.BeginFilePostRequest), this);
}
}
I have Stream in my silverlight application and try to call PostFile by click submit button:
private void submit_button_Click(object sender, RoutedEventArgs e)
{
//...
HttpHelper helper = new HttpHelper(memory_stream);
helper.PostFile();
}
But mysite recieve request without file. It just has ContentLength 13. What's problem?
Try Flush on your writer before exiting the using block, you should also call Close on the stream retrieved from EndGetRequestStream.
you HAVE TO Flush and Dispose HTTP request stream and all downstream streams, then it works.

How can I save and open a file in winForms?

I have this application where I use windowsForm and UserControl to draw some diagrams. After I am done I want to save them or I want to open an existing file that I created before and keep working on the diagram. So, I want to use the save and open dialog File to save or open my diagrams.
EDIT:
this is what i have :
//save the object to the file
public bool ObjectToFile(Object model, string FileName)
{
try
{
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, model);
byte[] _ByteArray = _MemoryStream.ToArray();
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray.ToArray(), 0, _ByteArray.Length);
_FileStream.Close();
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return false;
}
//load the object from the file
public Object FileToObject(string FileName)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
long _TotalBytes = new System.IO.FileInfo(FileName).Length;
byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);
_FileStream.Close();
_FileStream.Dispose();
_FileStream = null;
_BinaryReader.Close();
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_MemoryStream.Position = 0;
return _BinaryFormatter.Deserialize(_MemoryStream);
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return null;
}
and now I want to do this but it's not working
public void save()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.OpenFile() != null)
{
ObjectToFile(model, saveFileDialog1.FileName);
}
}
}
but if I try without the fileDialog and i just use
ObjectToFile(model, "d:\\objects.txt");
this works. And I want to save it where I want and with my own name.
Check out the SaveFileDialog and OpenFileDialog classes. They are pretty similar, and can be used like this:
using(SaveFileDialog sfd = new SaveFileDialog()) {
sfd.Filter = "Text Files|*.txt|All Files|*.*";
if(sfd.ShowDialog() != DialogResult.OK) {
return;
}
ObjectToFile(sfd.FileName);
}
The mechanics of actually saving your file are, obviously, outside the scope of this answer.
Edit: I've updated my answer to reflect the new information in your post.

Resources