I am trying create and write to a text file in a C# application using the following code
System.IO.Directory.CreateDirectory(Server.MapPath("~\\count"));
using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create))
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt"))
{
sw.Write("101");
}
string _count = System.IO.File.ReadAllText("~/count/count.txt");
Application["NoOfVisitors"] = _count;
but I get an error:
The process cannot access the file 'path' because it is being used by another process.
What is my error?
To create a file in a 'C' program following syntax is used, FILE *fp; fp = fopen ("file_name", "mode"); In the above syntax, the file is a data structure which is defined in the standard library. fopen is a standard function which is used to open a file.
File Input and Output in C 1) Create a variable to represent the file. 2) Open the file and store this "file" with the file variable. 3) Use the fprintf or fscanf functions to write/read from the 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.
You're trying to open the file twice; your first using
statements creates a FileStream
that is not used, but locks the file, so the second using
fails.
Just delete your first using
line, and it should all work fine.
However, I'd recommend replacing all of that with File.WriteAllText
, then there would be no using in your code, it'd be much simpler.
var dir = Server.MapPath("~\\count");
var file = Path.Combine(dir, "count.txt");
Directory.CreateDirectory(dir);
File.WriteAllText(file, "101");
var _count = File.ReadAllText(file);
Application["NoOfVisitors"] = _count;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With