2011-10-07 102 views
1

我的第一個問題就在,如果我聲明我FILESTREAM等以這種方式問題FILESTREAM,StreamReader的和StreamWriter

filestream file; 
streamreader file_in; 
streamwriter file_out; 

try 
{ 
    file = new filestream("data.txt", FileMode.OpenOrCreate); 
    file_in = new streamreader(file); 
    file_out = new streamwriter(file); 
} 
catch(IOException exc) 
{ 
    Console.WriteLine(exc.Message); 
} 

的形式拋出一個錯誤,說:「使用未分配的局部變量」,我覺得這奇怪的是因爲所有的流都是在try塊外面聲明的,但是在main裏面,所以它們應該存在於main裏面。

我的另一個問題是,如果我刪除try/catch塊並將流聲明爲一行(例如:FileStream file = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);),我從文件中讀取的確可行,但我無法寫入文件。我的寫入文件功能如下:

public bool write_to_file(ref StreamWriter file_out) 
    { 
     if (this.is_empty == true) 
     { 
      Console.WriteLine("error, there is nothing to write."); 
      Console.WriteLine("press any key to continue..."); 
      Console.ReadKey(); 
      return false; 
     } 

     try 
     { 
      string temp = this.is_empty + "," + this.movie_title + "," + this.year_released + "," + this.publisher + "," + 
       this.length + "," + this.acting_rating + "," + this.music_rating + "," + this.cinematography_rating + "," + 
       this.plot_rating + "," + this.duration_rating + "," + this.total_rating; 
      file_out.WriteLine(temp); 
      return true; 
     } 
     catch (IOException exc) 
     { 
      Console.WriteLine(exc.Message); 
      Console.WriteLine("press any key to continue..."); 
      Console.ReadKey(); 
      return false; 
     } 
    } 

任何幫助將不勝感激,謝謝。

+0

任何你把'FileStream'改成'filestream'的原因? –

+0

-1,您發佈的代碼(第一部分)是否__not__給出您聲稱的錯誤。 –

回答

3

你需要在頂部值分配給你的變量,即使它只是空

FileStream file  = null; 
StreamReader file_in = null; 
StreamWriter file_out = null; 
+0

謝謝,它解決了try/catch塊錯誤,但是,我的streamwriter似乎仍然不想將適當的數據寫入文件。你能否提供任何協助? –

+0

不正確。這可能是個好主意,但這裏並不需要。 –

+0

好吧,只要我改變它的解決方案,它開始再次工作。所以出於某種未知的原因,它一定是必要的(並且它讓我感到不知所措)。 –

4

好,他們聲明,但未分配的......所以,無論是將其設置爲空或只是做一切在一起。

try 
{ 
    using(var file = new FileStream("data.txt", FileMode.OpenOrCreate)) 
    using(var file_in = new StreamReader(file)) 
    using(var file_out = new StreamWriter(file)) 
    { 
     // Do your thing 
    } 
} 
catch 
{ 
    throw; 
} 
+0

謝謝,它解決了try/catch塊錯誤,但是,我的streamwriter似乎仍然不想將適當的數據寫入文件。你能否提供任何協助? –

+1

好的,顯示全文以及你在讀寫器上做什麼(以及何時調用其他方法)。 – canon

0

在關閉文件之前,請嘗試刷新輸出流和文件。

file_out.Flush(); 
file.Flush(); // may be redundant but won't hurt 
+0

謝謝,我把一個file_out.flush()放在writeline後面,強制它在緩衝區中寫入什麼文件並清除緩衝區,並且在文件關閉之前添加了你所說的內容,以確保它能夠正常工作。 –

+0

@DamonSwayn:乾杯!很高興有幫助。請不要忘記提供您認爲有用的答案,並且可以選擇接受解決問題的答案! – sehe