2013-07-24 70 views
4

剛開始編寫單元測試,我現在,阻斷這種情況:字符串轉換爲FILESTREAM在C#

我有具有FileStream對象的方法,我試圖以一種「串」傳遞給它。 所以,我想我的字符串轉換爲的FileStream和我這樣做:

File.WriteAllText(string.Concat(Environment.ExpandEnvironmentVariables("%temp%"), 
@"/test.txt"), testFileContent); //writes my string to a temp file! 


new FileStream(string.Concat(Environment.ExpandEnvironmentVariables("%temp%"), 
    @"/test.txt"), FileMode.Open) //open that temp file and uses it as a fileStream! 

關閉文件呢!

但是,我想必須有一個非常簡單的替代方案來將字符串轉換爲fileStream。

歡迎提出建議! [注意,這個問題在stackoverflow中有其他答案,但似乎沒有一個簡單的解決方案]

在此先感謝!

回答

10

首先將您的方法更改爲允許Stream而不是FileStreamFileStream是一個實現,我記得,它沒有添加任何方法或屬性,只是實現了抽象類Stream。然後使用下面的代碼,你可以轉換stringStream

public Stream GenerateStreamFromString(string s) 
{ 
    MemoryStream stream = new MemoryStream(); 
    StreamWriter writer = new StreamWriter(stream); 
    writer.Write(s); 
    writer.Flush(); 
    stream.Position = 0; 
    return stream; 
} 
+0

問題是我無法更改代碼。這是一個已編譯的庫,我沒有源代碼! –

+0

因此,用你自己的類覆蓋'FileStream'。 –

+0

你將不得不嘲笑文件流,然後如其他人提到 – lloydom

0

至於FileStream類的文件提供了一個流,因此它的構造函數需要的文件,模式,權限參數等的路徑文件讀入到流,因此它被用來從文件讀入流中的文本。如果我們需要先將字符串轉換爲流,那麼我們需要將字符串轉換爲字節數組,因爲流是一個字節序列。以下是代碼。

//Stream is a base class it holds the reference of MemoryStream 
      Stream stream = new MemoryStream(); 
      String strText = "This is a String that needs to beconvert in stream"; 
      byte[] byteArray = Encoding.UTF8.GetBytes(strText); 
      stream.Write(byteArray, 0, byteArray.Length); 
      //set the position at the beginning. 
      stream.Position = 0; 
      using (StreamReader sr = new StreamReader(stream)) 
         { 
          string strData; 
          while ((strData= sr.ReadLine()) != null) 
          { 
           Console.WriteLine(strData); 
          } 
         }