2012-07-02 100 views
2

我一直在尋找許多網站現在的答案,但所有工作的答案只適用於richTextbox,我使用普通的文本框。我試圖將文本框的內容保存到一個選擇的文件中,但由於某種原因文件沒有保存,我不知道問題是什麼。這是「保存」菜單項的代碼:文本文件沒有得到保存,但沒有錯誤(C#)

private void saveToolStripMenuItem_Click(object sender, EventArgs e) 
    { 

     SaveFileDialog ofd = new SaveFileDialog(); 
     ofd.Title = "Save"; 
     ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*"; 
     if (ofd.ShowDialog() == DialogResult.OK) 
     { 
      try 
      { 
       //I don't know what to make of this, because clearly this doesn't work 
       File.WriteAllText(@"./TestFile.txt", MainTextbox.Text); 
      } 
      catch (Exception ex) 
      { 
       MainTextbox.Text += ex; 
      } 
     } 
    } 

沒有錯誤。

+7

你不應該保存到'SaveFileDialog'中選定的文件嗎? –

+0

@TimS。當然會打敗目標,也就是目前設定的方式。我會打電話給你的建議一個答案。 – erodewald

+3

你確定沒有例外嗎?也許它正在吞噬鏈條上的某個地方?您正試圖在C:\驅動器的根目錄下創建一個文件,因此很有可能(並且很可能,除非您採取其他措施)您沒有權限在其中創建文件。我的假設是你使用硬編碼的文件名來測試你是否可以創建一個文件,否則,上面Tim S的評論可能是解決方案。 –

回答

5

您應該保存到您的SaveFileDialog中選定的文件,如OpenFile()檢索到的文件。這個例子爲我工作:

SaveFileDialog ofd = new SaveFileDialog(); 
ofd.Title = "Save"; 
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*"; 
if (ofd.ShowDialog() == DialogResult.OK) 
{ 
    using (var fileStream = ofd.OpenFile()) 
    using (var sw = new StreamWriter(fileStream)) 
     sw.WriteLine("Some text"); 
} 

在你的代碼,你讓用戶選擇一個文件保存到,然後忽略並將其寫入一個硬編碼位置。有可能您的應用沒有權限執行此操作,但應用程序應具有寫入用戶所選位置的權限。

+0

這解決了我的問題。非常感謝你! – DutchLearner

0

我認爲它的訪問被拒絕的問題..嘗試用 'd' 車程

這是工作例子..。 WriteAllText當文件已經存在,如果文件已經存在,然後使用AppendAllText

using System; 
using System.IO; 
using System.Text; 

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

     // This text is added only once to the file. 
     if (!File.Exists(path)) 
     { 
      // Create a file to write to. 
      string createText = "Hello and Welcome" + Environment.NewLine; 
      File.WriteAllText(path, createText); 
     } 

     // This text is always added, making the file longer over time 
     // if it is not deleted. 
     string appendText = "This is extra text" + Environment.NewLine; 
     File.AppendAllText(path, appendText); 

     // Open the file to read from. 
     string readText = File.ReadAllText(path); 
     Console.WriteLine(readText); 
    } 
} 
0

首先,將文件保存無關與將文本從,豐富的文本框或普通文本框來工作。

正如Brian S.在評論中所說的那樣,很可能存在例外,因爲您正在寫入C驅動器。您應該使用相對路徑:"./MyTest.txt"

相關問題