您的位置:首页 > 其它

该进程无法访问文件,因为该文件正由另一进程使用!

2007-09-21 11:38 267 查看
用asp.net文件读写操作时错误: 该进程无法访问文件,因为该文件正由另一进程使用!

在此引用MSDN中的示例解决:

1 using System;

2 using System.IO;

3

4 class Test

5 {

6 public static void Main()

7 {

8 string path = @"c:\MyTest.txt";

9 // This text is added only once to the file.

10 if (!File.Exists(path))

11 {

12 // Create a file to write to.

13 using (StreamWriter sw = File.CreateText(path)) //在 using 语句中创建一个实例,确保退出 using 语句时在对象上调用 Dispose。

14 {

15 sw.WriteLine("Hello");

16 sw.WriteLine("And");

17 sw.WriteLine("Welcome");

18 }

19 }

20

21 // This text is always added, making the file longer over time

22 // if it is not deleted.

23 using (StreamWriter sw = File.AppendText(path)) {

24 sw.WriteLine("This");

25 sw.WriteLine("is Extra");

26 sw.WriteLine("Text");

27 }

28

29 // Open the file to read from.

30 using (StreamReader sr = File.OpenText(path))

31 {

32 string s = "";

33 while ((s = sr.ReadLine()) != null)

34 {

35 Console.WriteLine(s);

36 }

37 }

38 }

39 }
注意上面的using语句一定要用,否则就会出现上面的错误,希望对各位有帮助!----我是菜鸟
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐