Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing in files ASP.NET C# and NOT locking them afterwards

Tags:

c#

asp.net

I am getting this error: The process cannot access the file (...) because it is being used by another process. I have tried to use File.WriteAllText;

StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();

;

using (FileStream fstr = File.Create(myfilepath))
                {
                StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();
                fstr.Close();
                }

All I am trying to do is to access a file, write on it, then close it. I might be making a silly mistake but I would like to understand what I am doing wrong and why. How to make sure that the file is closed and not to cause this error again.

Helped by the answers so far I did this:

using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
                {
                    StreamWriter sw = new StreamWriter(fstr);
                    sw.Write(mystring);
                    sw.Close();


                }

It seems to be better because it seems to close/stop the process of my file if I try to access another file on the second time I access the page. But if I try to access the same file on a second time, it gives me the error again.

like image 512
Jenninha Avatar asked Jul 27 '12 11:07

Jenninha


People also ask

How do you create a file and write it in C#?

The CreateText() method of the File class is used to create a text file in C#. The File. CreateText() method takes a full specified path as a parameter and creates a file at the specified location for writing UTF-8 encoded text. I​f any such file already exists at the given location, this method opens the file.

How do I write to a text file?

Steps for writing to text files First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

Where does StreamWriter write to?

StreamWriter. WriteLine() method writes a string to the next line to the steam. The following code snippet creates and writes different author names to the stream.


1 Answers

Why not just use:

System.IO.File.WriteAllText(myfilepath, mystring");

That should not lock your file.

Internally WriteAllText uses FileShare.Read and releases that lock as soon as it is done writing.

like image 178
nunespascal Avatar answered Nov 14 '22 23:11

nunespascal