2012-07-29 66 views
1

下面是我的教练和我的朋友Win 7的给它工作得很好。我已经试过我的工作笔记本电脑和我的个人桌面......不断挖掘出以下错误StreamReader的问题找到文件

我不明白......我尽量更改权限的目录给大家只是踢去......它适用于他的复制粘贴,但不是我的。

“找不到路径的一部分 'C:\用户\ Wookie \我的文档\'。”

using System; 
using System.IO; 

class Program 
{ 
static void Main() 
{ 

// This line of code gets the path to the My Documents Folder 
string environment = System.Environment.GetFolderPath 
(System.Environment.SpecialFolder.Personal) + "\\"; 

Console.WriteLine("Enter a file name in My Documents: "); 
string input = Console.ReadLine(); 

// concatenate the path to the file name 
string path = environment + input; 

// now we can use the full path to get the document 
StreamReader myFile = new StreamReader(path); 
int n = int.Parse(myFile.ReadLine()); 
Console.WriteLine("read {0}", n); 

Console.ReadLine(); 
}//End Main() 
}//End class Program 
+0

你说它可以在你的朋友Windows 7上正常工作,你试图在哪个操作系统上运行它。 – 2012-07-29 22:40:31

+0

添加一个'Console.Writeline(路径)'并仔细检查它是否存在。 – 2012-07-29 22:42:32

+0

运行Win 7以及 – Dan 2012-07-29 22:43:04

回答

3

尝试的文件是否确实但从程序的观点存在。当然,将yourfile.txt替换为您正在查找的文件的文件名。

string path = Path.Combine(System.Environment.GetFolderPath 
    (System.Environment.SpecialFolder.Personal), "yourfile.txt"); 
Console.WriteLine(File.Exists(path)); 

如果没有,请在文件系统资源管理器中尝试。否则,你确定你输入的文件名是否正确?尝试暂时对其进行硬编码。上面的代码还显示了如何组合路径(请注意缺少自动插入的斜杠(\))以及如何检查文件(或使用Directory.Exists()的目录)是否存在。这可能有助于找出问题所在。

+0

C:\ Users \ Wookie \ Documents \和文件是test.txt – Dan 2012-07-29 22:45:11

+0

有没有一种特殊的方式来访问用户下我的文档。我去了属性,并复制了写在那里的确切目录,它仍然表明它不存在... – Dan 2012-07-30 18:56:24

2

仅仅为了良好的编码习惯,使用Path.Combine来连接路径。 而Path.DirectorySeparatorChar代替“\”作为一个很好的做法。

例子:

string path = Path.Combine(environment, input);