2011-03-20 39 views
-1

如何讀取C#中的文件?如何讀取文件

什麼是可用方法?

+0

我一直在嘗試文本文件。 – Sadique 2011-03-20 22:17:29

+1

我不確定這種問題是否適合SO。網絡上有無數的資源關於此.. – 2011-03-20 22:28:48

+0

另請參見[這個答案](http://stackoverflow.com/questions/181634/simplest-efficient-ways-to-read-binary-and-ascii-files-to -string-or-similar-in-v/181766#181766) – Brian 2011-03-21 13:28:19

回答

4

嗯,還有的File類。

+0

txtSourceFileName是一個文本框 - 這是行不通的...請幫助 string text = System.IO.File.ReadAllText(txtSourceFileName) – Sadique 2011-03-20 22:21:40

+1

@ user667389:關閉。您可能會收到有關傳遞給「ReadAllText」方法的類型錯誤的錯誤。你想引用'TextBox'的'.Text'屬性來獲得它的內容。嘗試'字符串文本= System.IO.File.ReadAllText(txtSourceFileName.Text);' – David 2011-03-20 22:23:49

+0

它給了我一個錯誤: txtSourceFileName.Text是空 - 我想這個值由用戶輸入該怎麼辦? – Sadique 2011-03-20 22:28:05

4

模糊的問題,但在給定的信息,並假設文本文件:

string fileData = System.IO.File.ReadAllText(@"C:\path\to\your\file.txt"); 

不過,如果你正在閱讀的二進制文件,XML文件等等還有其他的方法。

+1

您正在查找文檔。前三個結果http://www.google.com/search?q=.net+how+to+read+text+files。 – SLaks 2011-03-20 22:18:37

+2

@ user667389:他做到了。他提供了一行代碼,將整個文本文件讀入一個字符串。實際上,他非常友善。如果你需要更多,你可能希望更具體。 – David 2011-03-20 22:19:51

4

您正在尋找System.IO的每一個課程,除了MemoryStream
有關更多詳細信息,請參閱the documentation

0

使用System.IO.StreamReader.ReadLine()方法將工作,如果你需要逐行的文本文件。

1

我經常閱讀txt文件用就是System.IO.StreamReader

StreamReader file = new StreamReader(@"C:\Windows\System32\etc.txt"); 

然後你就可以從文件中與

string blah = file.ReadLine(); 

string blahblah = file.Read() 
+0

如果我從文本框中獲取路徑,該怎麼辦? – Sadique 2011-03-20 22:24:46

+0

然後使用TextBox。文本代替 – benPearce 2011-03-20 22:27:04

+0

示例中的硬編碼路徑,以便它像新的StreamReader(TextBox1.Text); – MatthewSot 2011-03-20 22:33:56

1
include System.IO; //The input/output class in C# .NET 

//Main Class etc. 
StreamReader sr = new StreamReader(string Path); 
string output = sr.Read(); //output data 

閱讀閱讀時,C#往往非常挑剔數據,所以我建議讀取二進制數據,而不是使用StreamReader。