hello!
i could i force to close the file when it is opened?
tnx bunch
Printable View
hello!
i could i force to close the file when it is opened?
tnx bunch
if you were using a StreamReader , it would be something like
Code:sr.Close();
e.g.
StreamWriter sw = File.AppendText(Path);
sw.WriteLine(txtInput.Text);
sw.Close();
here is the code:
try
{
StreamReader sr = new StreamReader(txtPath.Text);
string lineHeader = sr.ReadLine(); //disregard the heading
string lineContents = sr.ReadLine(); //read the contents until EOF
while (lineContents != null)
{
string[] strValues = lineContents.Split(',');
listBox1.Items.Add(strValues[0] + " - " + strValues[1]);
lineContents = sr.ReadLine();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
if the above Try found that the file is opened, how could close it on Catch?
or close the file and then read the contents?
EDIT: You should catch System.IO Exceptions before the general exception. And you shouldn't show ex.Message in a message box, you should do something to handle the error and show a meaningful message to the user
Code:StreamReader sr = new StreamReader(txtPath.Text);
try
{
string lineHeader = sr.ReadLine(); //disregard the heading
string lineContents = sr.ReadLine(); //read the contents until EOF
while ( lineContents != null )
{
string[] strValues = lineContents.Split(',');
listBox1.Items.Add(strValues[0] + " - " + strValues[1]);
lineContents = sr.ReadLine();
}
}
catch ( Exception ex )
{
//MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
sr.Close();
}
You should be making use of 'using' blocks so there's no need for a 'finally' block:The StreamReader will be disposed and the file closed at the last closing brace no matter what happens inside the 'using' block. You should do this with all short-lived objects that require disposing.C# Code:
using (StreamReader sr = new StreamReader(txtPath.Text)) { try { } catch { } }
Maybe the original poster is saying that when they try to open the file, it errors because it is open not because he (she) opened it and didn't close it but because some other user/process has the file open.
I'm not sure. but is the using keyword available in all versions of C#?Quote:
Originally Posted by jmcilhinney
It may not be supported before 2005 but if someone's not going to bother specifying their version then I'll assume they're using the latest.Quote:
Originally Posted by ComputerJy
tnx for sharing ur ideas...
to let this discussion end, when i found out the file is open
i will close it because it keeps showing the message "already use by the other process".
tnx to all of you