文件操作设定路径的一些注意

来源:互联网 发布:java web项目开发案例 编辑:程序博客网 时间:2024/05/16 04:52

背景:近来一段码进行读写文件的时候,意外的发现在 XP 系统下文件读取不成功, 后来发现是由于路径的设定不正确。

这里举例说明下:


我原本想在应用程序的目录下创建一个 test.txt 文件进行读写操作。

<span style="font-size:14px;">  FileStream fs = new FileStream(“test.txt", FileMode.Append);</span>


这样的一行代码在自己调试的时候,怎样也没有发现有问题,文件的路径也正确的在当前执行文件的目录。

但是这样忽略一个重要的问题: 当前目前目录不一定就是当前执行文件的目录,所以这种没有写完整路径名,而只写文件名的做法是不对的。。。。

因为当前目录可以用  System.IO.Directory.SetCurrentDirectory 来改变,所以

<span style="font-size:14px;"> System.IO.Directory.SetCurrentDirectory("d:"); // 改变当前目录为 d 盘 FileStream fs = new FileStream(“test.txt", FileMode.Append);</span>

像这样,创建出的 test.txt 文件是放在 D 盘下面。。。


因此,碰到文件操作的时候,最好指定文件的完整路径。 如想在当前执行文件下创建文件,可以如下操作

<span style="font-size:14px;"> string currentFolder = System.IO.Path.GetDirectoryName( System.Windows.Forms.Application.ExecutablePath); string filePath = currentFolder + "\\test.txt"; FileStream fs = new FileStream("ttt.txt", FileMode.Append);</span>


0 0