2010-12-14 34 views
1

Beloew是我的代碼,我想保存一些信息用戶鍵保存到文件中,我在調試後如何繼續遇到Ioexception錯誤並單擊保存按鈕..請親切地說。我猜這與文件夾有關,但絕對沒有想法..當選擇保存按鈕時出現IoException錯誤

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 

namespace ASSISNMENTTT 
{ 
    public partial class Registeration : Form 
    { 
     public Registeration() 
     { 
      InitializeComponent(); 
     } 

     private void Btn_Save_Click(object sender, EventArgs e) 
     { 
      // This is the button labeled "Save" in the program. 
      // 
      File.WriteAllText("C:\\demo.txt", Tb_Admin.Text); 
      File.WriteAllText("C:\\demo.txt", Tb_Name.Text); 
      File.WriteAllText("C:\\demo.txt", Tb_Gender.Text); 
     } 
    } 
} 
+2

你可以給堆棧跟蹤和異常消息嗎? – 2010-12-14 01:50:39

+0

嘗試將文件保存到其他位置,例如在用戶配置文件中。您可能沒有寫入權限C:\ – shf301 2010-12-14 02:08:57

+0

正如有人在我刪除的答案中指出的那樣 - 如果存在權限問題而不是IOException,則會得到UnauthorizedAccessException。我的記憶一定要去! – 2010-12-14 02:14:01

回答

0

很可能你是在Win7或Vista上,並且無法訪問c:\驅動器。

+0

訪問路徑'C:\ demo.txt'被拒絕。 – 2010-12-14 03:02:44

+0

@Jun,所以是的,我是對的。默認情況下,您無權訪問c驅動器的根目錄。嘗試將文件保存到c:\ users \ {your_user_name} \ desktop \ demo.txt – AngryHacker 2010-12-14 04:20:25

+0

嗨生氣的黑客..你的用戶名會引用我的電腦名稱? – 2010-12-15 01:20:25

0

如果您的應用程序有權訪問C:\驅動器,則demo.txt可能標記爲只讀,因爲WriteAllText將嘗試覆蓋該文件。

此代碼顯示一個UnauthorizedAccessException,其中包含相同的錯誤文本,因爲您在評論您的問題和其他答案。

static void Main(string[] args) 
{ 
    var demoTxt = new FileInfo("C:\\demo.txt"); 
    demoTxt.Attributes |= FileAttributes.ReadOnly; 

    WriteAllText("should succeed"); 


    try 
    { 
     demoTxt.Attributes |= FileAttributes.ReadOnly; 
     WriteAllText("should fail"); 
    } 
    catch (UnauthorizedAccessException uae) 
    { 
     Debug.WriteLine(uae.ToString()); 
    } 
} 

static void WriteAllText(string text) 
{ 
    // This is the button labeled "Save" in the program. 
    // 
    File.WriteAllText("C:\\demo.txt", text); 
} 

爲了將來的參考,這可能會幫助您提供更多關於SO帖子的信息。

private void Btn_Save_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      // This is the button labeled "Save" in the program. 
      // 
      File.WriteAllText("C:\\demo.txt", Tb_Admin.Text); 
      File.WriteAllText("C:\\demo.txt", Tb_Name.Text); 
      File.WriteAllText("C:\\demo.txt", Tb_Gender.Text); 
     } 
     catch(IoException ex) 
     { 
      //View the Output Window, copy the text to your question 
      System.Diagnostics.Debug.WriteLine(ex.ToString()); 
     } 
    } 
+0

Hi Austin,我必須首先在名爲demo的c盤創建一個新文件夾嗎? – 2010-12-14 04:04:24

+0

沒有文件夾是必要的。該文件是隻讀的,是基於您的意見的選項。 – 2010-12-14 04:15:33

+0

即時通訊仍然遇到同樣的錯誤,它確定哪裏出了問題..但許多th你奧斯汀幫助你呈現 – 2010-12-14 04:39:23

相關問題