【发布时间】:2012-08-02 04:09:45
【问题描述】:
我有一个 C# Visual Studio 2008 表单,它需要读取相关文件 'character/attacks.txt' 的内容 File.Exists() 在我运行它时返回 false,即使我确定我的目录已排序.代码:
try
{
System.IO.StreamReader file = new System.IO.StreamReader("character/attacks.txt");
int counter = 0;
int numberOfLines = 0;
string line;
while ((line = file.ReadLine()) != null) { numberOfLines++; }
string[] attacks = new string[numberOfLines];
while ((line = file.ReadLine()) != null) { attacks[counter] = line; counter++; }
file.Close();
print(attacks.ToString());
}
catch (Exception ex)
{
print("ERROR"); print("Did you edit any files?"); print(ex.ToString());
}
异常错误:
System.IO.FileNotFoundException: Could not find file 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt'.
File name: 'D:\Users\Andrey\Desktop\Turn\character\attacks.txt'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at TurnByTurn.Form1.button1_Click(Object sender, EventArgs e) in D:\Users\Andrey\Desktop\C#\TurnByTurn\TurnByTurn\Form1.cs:line 52
我正在从 Python 移植我的代码,并且从未遇到过任何问题。提前致谢!
【问题讨论】:
-
你确定文件存在这里吗:D:\Users\Andrey\Desktop\Turn\character\attacks.txt
-
是的,确实如此。我什至把characters文件夹放到debug文件夹下,还是不行。
-
嗯,这很奇怪。计算机似乎坚信“D:\Users\Andrey\Desktop\Turn\character\”目录中没有“attacks.txt”文件,但您说有。你们中的一个一定是错的。您确定您的文件实际上具有
.txt扩展名,而不是.txt.somethingelse扩展名吗?如果你在 Windows shell 中关闭了文件扩展名,你可能会错过这个。这是同样的问题this guy had。 -
@CodyGray 谢谢!我的文件是 Attacks.txt.txt 如果您将评论添加为答案,我会标记它。
-
很高兴工作;我添加了一个答案。
标签: c# visual-studio-2008 file-io