"File in use" error when writing to text file - c#

I'm getting the error The process cannot access the file 'C:\Users\Ryan\Desktop\New folder\POSData.txt' because it is being used by another process. when I try to create a file and then write to it. What process is using the file?? I checked for a file.close to call after I create the file, but it doesn't exist. How do I get past this? Thanks!
Heres my code:
MessageBox.Show("Please select a folder to save your database to.");
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
if (!File.Exists(databasePath + "\\POSData.txt"))
{
File.Create(databasePath + "\\POSData.txt");
}
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Edit: Only happens when creating the file. If it already exists, no error occurs.

Actually, don't even bother using File.Create. The reason you're getting that error is because File.Create is opening up a stream on that text file.
string filePath = "databasePath + "\\POSData.txt"";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}

You are keeping the file open when you call File.Create (i.e. you never close the file).
StreamWriter will create the file for you if it doesn't exist, so I wouldn't bother checking yourself. You could just remove the code that checks whether it exists and creates it if it doesn't.
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Note that if the file doesn't exist, the second bool parameter in the StreamWriter constructor is ignored.

File.Create also opens the file for reading/writing. As such, you're leaving an open FileStream when you File.Create.
Assuming that overwriting is OK, then you probably want to do something like this:
using (var fs = File.Create(databasePath + "\\POSData.txt"))
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine(stockCount);
}
given that File.Create:
Creates or overwrites a file in the specified path.

The File.Create returns a FileStream object that might need to be closed.
The FileStream object created by this method has a default FileShare
value of None; no other process or code can access the created file
until the original file handle is closed.
using (FileStream fs = File.Create(databasePath + "\\POSData.txt"))
{
fs.Write(uniEncoding.GetBytes(stockCount), 0, uniEncoding.GetByteCount(stockCount));
}

I used this and it worked
`File.AppendAllText(fileName,"");`
This creates a new file, writes nothing to it, then closes it for you.

Related

Creating a Txt-File and write to it [duplicate]

This question already has answers here:
C# exception. File is being used by another process
(7 answers)
Closed 5 years ago.
I want to create a text file then add the text of a TextBox to it.
Creating the text file works without any problems with following code:
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
File.Create(path);
}
But I get an error that the file is being used when I try to add the text to the text file. If the file already exist before it run the code I don't get this error and the TextBox.Text is added to the File.
I use this code to add the text to the text file:
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
}
Can you help me?
You don't actually have to check if the file exists, as StreamWriter will do that for you.
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
public StreamWriter(
string path,
bool append
)
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
You should use File.Create with using statement as it's locking the file on creating.So just change this line :
File.Create(path);
To this:
using (File.Create(path));
As you can see here, StreamWriter will actually create a file on specified path when it doesn't exist so it's useless to check for it.
I would suggest to remove the part which is creating the file and simply just start writing :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
But if you really want to create the file beforehand, remember to Dispose FileStream object created by File.Create call. Dispose call will automatically call Flush and Close for you so it's safe enough and you can do this in many ways like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
using ( File.Create(path) ) ; // This will generate warnings that you're not using the object and so on, but that's okay,
}
Or like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Dispose();
}
If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. So you don't need to check if the file exists or not.
You need to make sure the file is closed before you want to modify it.
You need to Move your
tw.Close();
Outside your using. Like so :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
tw.Close();
}
}
Edit : As pointed out, when the using ends the writer is disposed, so does not need manually closing.
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
}
}
This problem has been answered before in this thread.
Closing a file after File.Create
You will need to close the stream to the file before using it again.

Writting text to file c#.it's being used by another process

I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}

Can't get overwrite to work during File.Copy - unable to access error

I have been looking all at kinds of solutions for allowing an overwrite to occur from the following error
{"The process cannot access the file
'C:\pathway\filename.txt' because it is being
used by another process."}
I have tried, flushing, closing, GC.Collect(), ect... but I cannot seem to find a way pass this error.
I write a "temp" file as such
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (var line in detailLines)
{
sw.WriteLine(line);
}
sw.Flush();
sw.Close();
}
}
GC.Collect();
Then allow the user to specify their own destination where I copy the file above, to.
private void SaveFile()
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.FileName = fileName;
saveFile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (saveFile.ShowDialog() == DialogResult.OK)
{
System.IO.File.Copy(fileName, saveFile.FileName, true);
}
}
I can save as a new name fine, but if I attempt to save at the same pathway and name as the "temp" file, then it asks "if I want to replace this file" and after I click yes it crashes and throws that cannot access error.
Can someone explain how I can access and overwrite a file in the same destination?
Despite the fact that File.Copy method says that:
Overwriting a file of the same name is allowed.
It actually fails to succeed in it(looks like something else has been meant by this sentence):
try
{
String filePath = #"C:\TEMP\test.txt";
using (var fs = new StreamWriter(filePath))
{
fs.Write("data");
}
Console.WriteLine("File written");
// Fails
System.IO.File.Copy(filePath, filePath, true);
Console.WriteLine("File overwritten by itself");
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
So, you should probably just check whether the temp file and target file are the same and act accordingly:
if (fileName != saveFile.FileName)
System.IO.File.Copy(fileName, saveFile.FileName, true);
P.S.: There is always some probability of race conditions in the file system, but I don't think that you should really worry about it - dealing with it will just make your code more complex and improve nothing.

System IO Exception : the process cannot access the file because it is being used by another process c#

I have seen several post for this problem .I have implemented all suggestion like using flush() , close() method on streamwriter and connection Object,use GC.Collect() to force cleanup,, use using{} to autodispose
I am Doing Simple Get Operation from DB and write to text file ..here is my Code
public void WriteToFile(string ProductName)
{
//Already Got Data from DB and stored in "ProductName"
//saving in File
if (!File.Exists(path11))
{
File.Create(path11);
StreamWriter tw = new StreamWriter(path11);
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
else if (File.Exists(path11))
{
StreamWriter tw = new StreamWriter(path11, true);
tw.WriteLine(ProductName + "#" + DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
GC.Collect();
}
Another suggestion I Got is to lock the object ..But I cannot implement it ..
Any suggestion would be Helpful
File.Create creates the file and returns an open stream. You don't really need all that logic. Just use new StreamWriter(path11, true) which will create the file if it doesn't exist and append to it if it does. Also using is helpful:
public void WriteToFile(string ProductName)
{
//Get Data from DB and stored in "ProductName"
using (var tw = new StreamWriter(path11, true))
{
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
}
}
FileCreate returns a stream which you should use to instantiate StreamWriter:
var file = File.Create(path11);
StreamWriter tw = new StreamWriter(file);
And you should use using blocks to make sure your stream and file is closed when you're finished writing.

The process cannot access the file when using StreamWriter

Basically I want to create a file if not existing then write message to it.
if (!File.Exists(filePath + fileName))
File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);
How to deal with this error?
The process cannot access the file 'c:\blahblah' because it is being used by another process.
File.Create opens a FileStream (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx).
As you didn't dispose it, the file remains locked and subsequent accesses to the file will fail because of this situation if these are performed from other handles (i.e. other FileStream or the whole StreamWriter).
This code demonstrates how you should work with IDisposable objects like FileStream:
if (!File.Exists(filePath + fileName))
{
File.Create(filePath + fileName).Dispose();
using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
{
}
}
Why not just use the StreamWriter constructor that takes in the file name?
StreamWriter sr = new StreamWriter(filePath + fileName);
From MSDN:
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created.
Very minor point but you could consider using Path.Combine when concatenating file names and folder paths.
Simplify your code by using single method to create and open a file:
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
MSDN: (File.OpenWrite Method)
Opens an existing file or creates a new file for writing.

Categories