Editor loading ...
Check the file and create it if the file does not exist
private void Existsfile (string FilePath)
{
if (! File.exists (FilePath))
File.create (FilePath);
The above wording will be the error, detailed explanation please see below ...
if (! File.exists (FilePath))
{
FileStream fs = File.create (FilePath);
Fs. Close ();
}
}
private void Button2_Click (object sender, System.EventArgs e)
{
Existsfile (Server.MapPath ("Test/weather.txt"))//Check whether the file exists
Reading files
StreamReader sr = new StreamReader (Server.MapPath ("Test/weather.txt"), System.Text.Encoding.Default);
Try
{
string input = Sr. ReadToEnd ();
Sr. Close (); <div class= "Msgfont" >//some of the platforms only \ \ Line for lines such as Mac,linux stream, Windows platform line wrap use \ r \ n
So even the. NET Framework has a System.Environment.NewLine; To implement line wrapping for different platforms. </div>
input = input. Replace ("\ r \ n", ""). Replace ("\ n", ""); Note: \ r \ n In the WinForm is a line, in the HTML document line, the display of the page will not be changed lines.
This. TextBox1.Text = input;
}
Catch
{
Response.Write ("<script>alert (' file read failed ');</script>");
}
}
private void Button1_Click (object sender, System.EventArgs e)
{
Existsfile (Server.MapPath ("Test/weather.txt"))//Check whether the file exists
Writing text
StreamWriter sr = new StreamWriter (Server.MapPath ("Test/weather.txt"), False,system.text.encoding.default);
Try
{
Sr. Write (this. TextBox1.Text);
Sr. Close ();
Response.Write ("<script>alert (' File write success ');</script>");
}
Catch
{
Response.Write ("<script>alert (' file write Failed ');</script>");
}
}
Error Explanation:
When there is no file in the specified path
The initial method: Start calling the
if (! File.exists (FilePath))
{
File.create (FilePath);
}
In the process of reading and writing:
private void Button2_Click (object sender, System.EventArgs e)
{
Existsfile (Server.MapPath ("Test/weather.txt"))//Check whether the file exists
Reading files
StreamReader sr = new StreamReader (Server.MapPath ("Test/weather.txt"), System.Text.Encoding.Default);
Try
{
string input = Sr. ReadToEnd ();
Sr. Close ();
input = input. Replace ("\ r \ n", ""). Replace ("\ n", "");
This. TextBox1.Text = input;
}
Catch
{
Response.Write ("<script>alert (' file read failed ');</script>");
}
}
"The file is written and is being used by another process, so the process cannot access the file"
Analysis of the problem is the reason: File.create (FilePath); A file was created and the process did not end
So it's time to create a file with a stream
if (! File.exists (FilePath))
{
FileStream FS1 = file.create (FilePath);
FS1. Close ();
}
When a stream creates a file and closes the stream, there is no such problem ...