Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create .txt file and write it c# asp.net

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?

like image 924
Happy .NET Avatar asked Oct 04 '14 07:10

Happy .NET


People also ask

How do you create a text file in C?

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.

How do I save a text file in C?

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.

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.


1 Answers

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;
like image 61
Danny Tuppeny Avatar answered Oct 16 '22 12:10

Danny Tuppeny