我在使用C#打开文件时遇到问题.
我有一个我需要阅读的文件,当我尝试使用C#打开它时,由于某种原因无法找到文件.
这是我的代码:
string fullpath = Directory.GetCurrentDirectory() +
string.Format(@"\FT933\FT33_1");
try
{
StreamReader reader = new StreamReader(fullpath);
}
catch(Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试打开的文件在里面Debug\FT933\FT33_1,没有扩展名.
每当我试图从同一目录中打开文本文件时,我都会这样做.
EDIT:
Run Code Online (Sandbox Code Playgroud)
为了更精确我认为我有的问题是我不知道如何打开一个没有扩展的文件(如果我改变文件有.txt扩展我确实设法打开它)
不要使用硬编码的路径或目录,而是使用内置函数来连接路径.
尝试
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string fullpath = Path.Combine(path, your_filename);
Run Code Online (Sandbox Code Playgroud)
请记住,当前目录可能不是您的应用程序!
更多,始终在using声明中包含流
using(StreamReader reader = new StreamReader(fullpath))
{
// Do here what you need
}
Run Code Online (Sandbox Code Playgroud)
所以你确定它会在必要时释放而不会浪费内存!
OP评论后编辑:
这是我的工作尝试:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string fullpath = Path.Combine(path, @"FT933\FT33_1");
if (File.Exists(fullpath))
{
using (StreamReader reader = new StreamReader(fullpath))
{
string ret = reader.ReadLine();
}
}
else
{
// File does not exists
}
Run Code Online (Sandbox Code Playgroud)
如果您属于// File does not exists部分,请确保该文件不在您要搜索的位置!
您确定您的文件没有隐藏的扩展名吗?
您确定OS或某些应用程序由于某种原因没有锁定文件吗?
在另一条评论后再次编辑:
打开命令提示符(使用Start-> Run-> CMD(enter))并运行以下命令:
dir "C:\Users\Stern\Documents\Visual Studio 2010\Projects\Engine\ConsoleApplication1\bin\Debug\FT933\*.*" /s
Run Code Online (Sandbox Code Playgroud)
并编辑显示结果的问题.