Reputation:
I am trying to write some text to the file using StreamWriter and getting the path for the file from FolderDialog selected folder. My code works fine if the file does not already exist. but if the file already exist it throws the Exception that the file is in used by other process.
using(StreamWriter sw = new StreamWriter(FolderDialog.SelectedPath + @"\my_file.txt")
{
sw.writeLine("blablabla");
}
Now if I write like this:
using(StreamWriter sw = new StreamWriter(@"C:\some_folder\my_file.txt")
it works fine with an existing file.
Upvotes: 1
Views: 3845
Reputation: 16
Try this
using (StreamWriter sw = File.AppendText(@"C:\some_folder\my_file.txt"))
{
sw.writeLine("blablabla");
}
it will only work in existing file, so to validate if the file is new or already exists, do something like
string path = @"C:\some_folder\my_file.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
//once file was created insert the text or the columns
sw.WriteLine("blbalbala");
}
}
// if already exists just write
using (StreamWriter sw = File.AppendText(@"C:\some_folder\my_file.txt"))
{
sw.writeLine("blablabla");
}
Upvotes: 0
Reputation: 887205
Check whether the file is in fact in use by some other process.
To do that, run Process Explorer, press Ctrl+F, type the filename, and click Find.
As an aside, the best way to accomplish this task is like this:
using(StreamWriter sw = File.AppendText(Path.Combine(FolderDialog.SelectedPath, @"my_file.txt")))
EDIT: Do NOT put a slash in the second argument to Path.Combine
.
Upvotes: 0
Reputation: 10772
This is a cheap answer, but have you tried this workaround?
string sFileName= FolderDialog.SelectedPath + @"\my_file.txt";
using(StreamWriter sw = new StreamWriter(sFileName))
{
sw.writeLine("blablabla");
}
The other thing I would suggest is verifying that FolderDialog.SelectedPath + "\my_file.txt" is equal to the hard coded path of "C:\some_folder\my_file.txt".
Upvotes: 0
Reputation: 49237
It may have to do with the way you are combining your path and filename. Give this a try:
using(StreamWriter sw = new StreamWriter(
Path.Combine(FolderDialog.SelectedPath, "my_file.txt"))
{
sw.writeLine("blablabla");
}
Also, check to make sure the FolderDialog.SelectedPath value isn't blank. :)
Upvotes: 2
Reputation: 2228
The file is already in use, so it cannot be overwritten. However, note that this message isn't always entirely accurate - the file may in fact be in use by your own process. Check your usage patterns.
Upvotes: 0