2011-12-02 158 views
2

我在用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); 
} 

我尝试打开该文件是内部Debug\FT933\FT33_1并没有得到推广。
每当我试图从同一个目录打开一个文本文件,我设法这样做。

EDIT: 

更精确的是,我认为这个问题,我有是,我不知道如何打开有没有一些推广(如果我更改文件有.TXT extention我不设法打开一个文件)

+1

\ FT933 \ FT33_1。 ? – st78

+0

当我推送属性时它没有扩展它说文件类型是文件 –

+3

在构建路径时,使用'Path.Combine'而不是串联。 – Oded

回答

8

不要使用硬编码路径或目录,而要使用内置函数来加入路径。
尝试

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
string fullpath = Path.Combine(path, your_filename); 

请记住,当前目录可能不是你的应用程序的一个!
更多,总是包括流在using声明

using(StreamReader reader = new StreamReader(fullpath)) 
{ 
    // Do here what you need 
} 

所以你一定需要在不浪费的内存将被释放!

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 
} 

如果您在// File does not exists节落下,确保文件是不是你正在寻找!
你确定你的文件没有隐藏的扩展名吗?
您确定操作系统或某个应用程序由于某种原因未锁定文件?

EDITED又陆续评论:
打开命令提示符(使用开始 - >运行 - > CMD(输入)),并运行此命令:

dir "C:\Users\Stern\Documents\Visual Studio 2010\Projects\Engine\ConsoleApplication1\bin\Debug\FT933\*.*" /s 

和编辑您的问题向我们展示结果。

+0

我有的问题是打开文件没有扩展我的文件类型是文件如果该文件有txt扩展我不会有这种问题。 –

+0

@NadavStern:你确定该文件没有任何扩展名吗?也许它隐藏在操作系统中。或者,也许该文件被锁定的操作系统... – Marco

+0

文件类型是文件100%确定 –