1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.IO;4 usingSystem.Linq;5 usingSystem.Text;6 usingSystem.Threading.Tasks;7 8 namespaceConsoleApp9 {Ten class Program One { A Static voidMain (string[] args) - { - Filestreamread (); the - //filestreamwrite (); - - + Console.readkey (); - } + A Private Static voidFilestreamwrite () at { -FileStream fs =NewFileStream (@". \res\test2.txt", FileMode.Create, FileAccess.Write); - byte[] bs = Encoding.UTF8.GetBytes (@"Hello"); -Fs. Write (BS,0, BS. Length); - FS. Close (); - FS. Dispose (); inConsole.WriteLine ("<"+ Encoding.UTF8.GetString (BS,0Bs. Length) +">"+"file has been written! "); - } to Private Static voidFilestreamread () + { -FileStream fs =NewFileStream (@". \res\test.txt", FileMode.Open, FileAccess.Read); the byte[] Buff =New byte[1024x768]; * intLen = fs. Read (Buff,0,1024x768); $ while(Len >0)Panax Notoginseng { - strings = Encoding.UTF8.GetString (buff,0, Len); the Console.WriteLine (s); +Len = fs. Read (Buff,0,1024x768); A } the } + } -}
View Code
The above is the code that uses FileStream to read and write text files, very simple, but some details worth noting.
1, my file path uses @ ". \res\test.txt" in the Solution Explorer view as follows:
“.” On behalf of the program running the current directory, if you copy the code directly, and copy the project folder structure, debugging run may error, because there is no corresponding resource in the program's running directory.
The workaround is to right-click the resource file you want to use, open the Properties option, and do as set:
Then recompile the project. At this point, open the project folder, into the bin directory, you will find in Debug or release (depending on the option you debug the program) a Res folder appears in the directory,
Open, there will be a test.txt file.
This is often the case with console applications and WinForm application development.
2, also, when using objects such as FileStream, pay attention to the release and collection of objects and resources, and then call the Close () method and the Dispose () method after the FileStream object is used, or use the Using clause.
Of course, the above is only the most basic information in the file read and write operations, other more in-depth use of details can refer to the MSDN documentation to continue research.
FileStream-based text file read and write operations in C #