روش کلی برای خواندن و نوشتن در فایل ها به صورت زیر است:
اول از همه فراموش نکنید که شما باید کتابخانه ی صحیح رو فراخوانی کنید:
1 using System.IO;
2
خواندن از فایل:
1 // *** Read from file ***
2
3 // Specify file, instructions, and privelegdes
4 file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);
5
6 // Create a new stream to read from a file
7 StreamReader sr = new StreamReader(file);
8
9 // Read contents of file into a string
10 string s = sr.ReadToEnd();
11
12 // Close StreamReader
13 sr.Close();
14
15 // Close file
16 file.Close();
17
18
19
نوشتن در فایل:
1 // *** Write to file ***
2
3 // Specify file, instructions, and privelegdes
4 FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
5
6 // Create a new stream to write to the file
7 StreamWriter sw = new StreamWriter(file);
8
9 // Write a string to the file
10 sw.Write("Hello file system world!");
11
12 // Close StreamWriter
13 sw.Close();
14
15 // Close file
16 file.Close();
17
18
19
* نکته ی خیلی مهم دیگه اینه که به محض اینکه دیگه به یک Stream نیاز نداشتید اون رو Close کنید، همینطور در مورد فایل ها.