【问题标题】:Saving Files error [duplicate]保存文件错误[重复]
【发布时间】:2016-12-22 13:32:20
【问题描述】:

需要注意这一点。

void testSave()
    {
        fileName = curMonth.Text + curYear.Text + ".csv";
        if (!File.Exists(path+fileName))
        {
            File.Create(path + fileName);
        }
        else if (File.Exists(path + fileName))
        {
         try
           {
               lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text;
                File.AppendAllText(path + fileName, lines + Environment.NewLine);
                TextWriter tw = new StreamWriter(path + fileName, true);
                tw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }             
    }

错误如下:

该进程无法访问文件“C:\Users...\File.csv”,因为它正被另一个进程使用。

我可以参考任何建议或解决方案吗?谢谢

【问题讨论】:

  • 可以删除除File.AppendAllText之外的所有代码行。您无需检查文件是否存在并手动创建文件。 File.AppendAllText 如果文件不存在则创建它。你也没有对你的TextWriter 做任何事情——它只是打开一个文件并关闭它而不写入它。
  • 我想检查文件是否存在,因为如果那是新文件,我想在数据进入之前添加一些标题,如果有什么办法吗?

标签: c# file save append


【解决方案1】:
  • File.Create(path + fileName); 未关闭,因此您无法重新打开。

  • 如果需要,请删除 else 关键字。

    void testSave()
    {
        fileName = curMonth.Text + curYear.Text + ".csv";
        if (!File.Exists(path+fileName))
        {
            try
            {
                File.Create(path + fileName).Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    
        try
        {
           lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text;
            File.AppendAllText(path + fileName, lines + Environment.NewLine);
            TextWriter tw = new StreamWriter(path + fileName, true);
            tw.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

【讨论】:

  • 仍然出现同样的问题...
  • 所有文件夹都创建了吗?
  • 是的,文件将被创建,但数据无法进入。
  • 嗨,我已经找到了解决方案。谢谢你。这样就解决了。 File.Create(path + fileName).Close();
  • 是的,完全一样,我标记为答案。谢谢你
猜你喜欢
  • 2013-04-19
  • 2018-04-13
  • 2011-05-22
  • 2021-10-03
  • 1970-01-01
  • 2020-03-25
  • 2016-03-28
  • 2011-12-04
  • 1970-01-01
相关资源
最近更新 更多