2010-12-14 60 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

相关问题