2017-10-20 74 views
1

我一直試圖瞭解幾個小時,爲什麼我的項目(完整桌面應用程序)不會讓我以適當的方式使用StreamWriter或StreamReader。問題是,如果我嘗試給任的StreamWriter或StreamReader的文件路徑(只是一個簡單的字符串),如下圖所示...StreamWriter和StreamReader無法正常工作

private readonly string _filePath = @"...Text.txt"; 

public string TestMethod(string text) 
{  
     // Does not accept a string as an argument, which it should based on the documentation 
     StreamReader reader = new StreamReader(); 
     text = reader.ReadToEnd(); 
     reader.Close(); 

     return text; 
} 

編輯:運行上面的代碼試圖讓所有的紅線消失將會在這篇文章中發佈錯誤。

下面是它目前看起來像(錯誤)

Wrong

Correct

以上就是它應該是什麼樣子的(正確的 - 與路徑放慢參數)

文檔:https://msdn.microsoft.com/en-us/library/f2ke0fzy(v=vs.110).aspx

...我得到各地的錯誤,如果我嘗試做另一種方式給它其他參數我得到一個錯誤說:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.' 

我試圖創建一個全新的解決方案,其中包括2個類庫(SO 2個項目1個解決方案,我想會是正確的說?),它非常有效。我這樣做是因爲我的另一個解決方案由3個類庫組成,所以我認爲如果可以的話,在再現問題時保持一致性是一個好主意。所以,我創建了一個簡單的文本文件,用一些文本填充它,並將其作爲新解決方案中TextBox中的屏幕輸出。這基本上讓我不知道現在該做什麼。

有誰知道什麼可能會導致此問題?

+1

這是一個什麼樣的項目,它是一個完整的桌面應用程序,或者這是一個應用程序商店應用程序或電話應用程序? –

+0

請將您的代碼和錯誤消息作爲文本發佈,而不是截圖。也就是說,你提到了「一個filePath(只是一個簡單的字符串)」 - 你能給出一些關於字符串的複雜性的例子,你擔心會導致StreamReader的問題? –

+1

什麼.net框架是您的項目定位?看看項目屬性。 – Igor

回答

2

很簡單,您所針對的.Net版本(.Net Standard 1.4)中的StreamReader類不支持具有文件路徑的構造函數。

您需要使用FileStream類來打開文件,然後使用StreamReader來讀取文件。

下面是從文檔複製一個例子:

https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.-ctor?view=netstandard-1.4

using System; 
using System.IO; 

class Test 
{ 

    public static void Main() 
    { 
     string path = @"c:\temp\MyTest.txt"; 

     try 
     { 
      if (File.Exists(path)) 
      { 
       File.Delete(path); 
      } 

      using (StreamWriter sw = new StreamWriter(path)) 
      { 
       sw.WriteLine("This"); 
       sw.WriteLine("is some text"); 
       sw.WriteLine("to test"); 
       sw.WriteLine("Reading"); 
      } 

      using (FileStream fs = new FileStream(path, FileMode.Open)) 
      { 
       using (StreamReader sr = new StreamReader(fs)) 
       { 

        while (sr.Peek() >= 0) 
        { 
         Console.WriteLine(sr.ReadLine()); 
        } 
       } 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The process failed: {0}", e.ToString()); 
     } 
    } 
} 
0

基礎上的評論,在當前的.NET的StreamReader沒有適當的過載,可以採取文件的路徑。您可以使用其他替代方法。您可以使用FileStream打開您想要的文件,然後使用StreamReader進行閱讀。