0
    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 has filename which i get from openfiledialog. like C:\Program Files (x86)\Microsoft\file.exe

when i debug this program. error happens. message is that The process cannot access the "c:\inputdata.txt" because it is being used by another process.

I don't understand why inputdata.txt is located in c:\ and why error is happening.

What is the reason for this error?

scopchanov
  • 7,966
  • 10
  • 40
  • 68

2 Answers2

0

You must close the FileStream after use it. Look at this : Closing a file after File.Create https://msdn.microsoft.com/en-us/library/aa328800(v=vs.71).aspx

Witzig Adrien
  • 102
  • 12
0

First read the text file then after update the file.

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

Then after right here appned or update logic here.bcz, If file is already open you can't write or update the file.

Anup Patil
  • 209
  • 2
  • 19