2011-12-02 200 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%確定 –