【问题标题】:System IO Exception was unhandled系统 IO 异常未处理
【发布时间】:2012-11-26 01:49:15
【问题描述】:

我正在尝试用 C# 开发我的第一个应用程序,我只是尝试从文件中读取和写入。我已经进行了数小时的研究,有导师试图教我,但这对我来说毫无意义。

我已经布置好表单的开头,并且我认为这是我正在使用的 StreamWriter 的正确语法,但文件名似乎在另一个进程中使用,我不知道是哪个.这是我正在使用的代码:

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

namespace CustomerApplication
{
    public partial class AddCustomerForm : Form
    {
        public AddCustomerForm()
        {
            InitializeComponent();
        }
    private void saveAndExitBtn_Click(object sender, EventArgs e)

    {
        StreamWriter sw = File.AppendText("test.csv");


           sw.WriteLine("Test for Hope");

        // next, retrieve hidden form's memory address
        Form myParentForm = CustomerAppStart.getParentForm();
        // now that we have the address use it to display the parent Form
        myParentForm.Show();
        // Finally close this form
        this.Close();
    }// end saveAndExitBtn_Click method

这是 Visual Studio 不喜欢的行:

StreamWriter sw = File.AppendText("test.csv");

提前感谢您的宝贵时间。

~TT

【问题讨论】:

  • 有什么异常? test.csv 是否在可执行文件所在的目录中?
  • +1 请发布例外。还有,你说的the file name seems to be used in another process, and I have no idea which.到底是什么意思呢?
  • @JamesEkema - 这可能来自异常消息,表明用户没有正确关闭流。

标签: c# csv io streamwriter


【解决方案1】:

这里有根据的猜测(基于但文件名似乎在另一个进程中使用) - 您打开文件进行写入,但您从不关闭它。因此,当您稍后尝试再次写入时,它会失败。

请注意,如果您在其他应用程序(例如记事本)中打开文件,也会发生这种情况。

您应该将流的创建放在using statement 中,以确保在您完成处理后它会关闭:

using(StreamWriter sw = File.AppendText("test.csv")
{
    sw.WriteLine("Test for Hope");

    ...
}

【讨论】:

  • 感谢大家的回答。没有更多的错误,但现在我很好奇如何让用户对表单的输入写入文件,而不仅仅是我的 WriteLine 代码将信息写入文件。然后我需要知道以正确的格式读取该文件。这是一个如此简单的任务,但又如此复杂,我的大脑感觉要爆炸了!我希望我有你所有的经验......
  • @JakeTully - 听起来你应该问一个新问题;)
【解决方案2】:

您确定您没有在其他地方打开文件吗?例如,在您进入该行代码之前,您可以尝试手动删除该文件,以查看是否有某个进程保留它。我输入它并且它工作。我建议将 Streamwriter 包装在 using 语句中并使用 FileInfo 对象。 FileInfo 对象上有一些不错的属性,就像您可以测试文件是否存在一样。你也可以这样做。

FileInfo fi = new FileInfo("C:\\test.csv");

if (fi.Exists)
  using (Streamwriter sw = fi.AppendText())
  {
     sw.WriteLine("tst");

     sw.Close();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多