Loading editor...
// Check the file. If the file does not exist, create
Private void existsfile (string filepath)
{
// If (! File. exists (filepath ))
// File. Create (filepath );
// The above writing method will report an error. For more information, see the following description .........
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
// Read the file
Streamreader sr = new streamreader (server. mappath ("test/weather.txt"), system. Text. encoding. Default );
Try
{
String input = Sr. readtoend ();
Sr. Close (); <Div class = "msgfont"> // some platforms only use \ n to indicate line breaks, such as MAC, Linux stream, and Windows platform use \ r \ n for line breaks.
// Even the. NET Framework has a & nbsp; system. environment. newline; To implement line feed for different platforms. </div>
Input = input. replace ("\ r \ n ",""). replace ("\ n", ""); // Note: \ r \ n contains line breaks in winform and line breaks in HTML documents, the displayed page does not contain line breaks.
This. textbox1.text = input;
}
Catch
{
Response. Write ("<SCRIPT> alert ('file read failed'); </SCRIPT> ");
}
}
Private void button#click (Object sender, system. eventargs E)
{
Existsfile (server. mappath ("test/weather.txt"); // check whether the file exists
// Write 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 written successfully'); </SCRIPT> ");
}
Catch
{
Response. Write ("<SCRIPT> alert ('file write failed'); </SCRIPT> ");
}
}
Error description:
// When no file exists in the specified path
// Initial method: Call
If (! File. exists (filepath ))
{
File. Create (filepath );
}
// When performing read/write operations:
Private void button2_click (Object sender, system. eventargs E)
{
Existsfile (server. mappath ("test/weather.txt"); // check whether the file exists
// Read the file
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 being used by another process when it is written, so the process cannot access the file"
// The cause of the analysis is: file. Create (filepath); the file is created and the process is not finished.
// Create a file using the stream
If (! File. exists (filepath ))
{
Filestream fs1 = file. Create (filepath );
Fs1.close ();
}
// When the stream creates a file and closes the stream, no similar problems will occur .....