【问题标题】:other process is still using this file其他进程仍在使用此文件
【发布时间】:2018-09-12 22:14:03
【问题描述】:
    public void button1_Click(object sender, EventArgs e)
    {
        //string item = ofd.FileName;
        ofd.InitialDirectory = "c:\\";
        ofd.Filter = "exe files (*.exe)|*.exe";
        ofd.Multiselect = true;
        ofd.RestoreDirectory = true;
        if (ofd.ShowDialog() == DialogResult.OK) 
        {
            listBox1.Items.Clear();
            string tmp = Path.Combine(Path.GetDirectoryName(listBox2.GetItemText(listBox2.Items)), "\\inputdata.txt");
            File.Create(tmp);
            using (File.Open(tmp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                ;
                foreach (string item in ofd.FileNames)
                {
                    string date = Path.GetFileName(item.Substring(10, 16));
                    string ite = item.Substring(0, item.IndexOf(".h2"));
                    listBox1.Items.Add(item);
                    if (File.ReadAllText(tmp).Contains(Path.GetFileName(item).Substring(10, 16)))
                    {
                        File.AppendAllText(tmp, Environment.NewLine);
                    }
                    if (item.IndexOf("MOD10A") >= 0)
                    {
                        if (File.ReadAllText(tmp).IndexOf(date) < 0)
                        {
                            File.AppendAllText(tmp, ite.Replace("MOD10A1.A", "ter_"));
                        }
                    }//
                    if (item.IndexOf("MYD10A") >= 0)
                    {
                        if (File.ReadAllText(tmp).IndexOf(date) < 0)
                        {
                            File.AppendAllText(tmp, ite.Replace("MYD10A1.A", "Aqu_"));
                        }
                    }
                    File.AppendAllText(tmp, ", " + item);
                }
            }
        }
    }

listbox2 具有我从 openfiledialog 获得的文件名。比如 C:\Program Files (x86)\Microsoft\file.exe

当我调试这个程序时。发生错误。消息是该进程无法访问“c:\inputdata.txt”,因为它正被另一个进程使用。

我不明白为什么 inputdata.txt 位于 c:\ 以及为什么会发生错误。

这个错误的原因是什么?

【问题讨论】:

  • input.txt 来自哪里/是什么创造了它?
  • 至少你应该关闭创建的流:using(File.Create(tmp)) {...}
  • inputdata.txt 是我在这个程序中创建的空 txt 文件。我想在里面写文字。

标签: c#


【解决方案1】:

【讨论】:

    【解决方案2】:

    先读取文本文件,然后更新文件。

            using (File.Open(tmp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            { 
                 /// Not right here a append txt logic 
             } 
             // Code File.AppendAllText
    

    然后在此处appned或更新逻辑here.bcz后,如果文件已打开,则无法写入或更新文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多