我编辑后如何关闭文本文件?

时间:2015-10-07 06:02:16

标签: c# visual-studio-2012

我在installer_input.txt中有一个文本文件checkedListBox2和一个form application。如果我在checkesListBox2中进行了一些更改,我想编辑文本文件。我有两部分代码,我知道这很长,但我需要一些帮助:

 private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory.ToString();
            var lin = (path + "config.ini").ToString();
            var lines = File.ReadAllLines(lin);
            string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
                        .Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
             string pathTemp = @"C:\temp\";
            string[] pathArr = InstallerFile.Split('\\');
            string[] fileArr = pathArr.Last().Split('\\');
            string fileArr1 = String.Join(" ", fileArr);


            string installerfilename = string.Format("{0}{1}", pathTemp, fileArr1);
            IEnumerable<string> inilines = File.ReadAllLines(installerfilename).AsEnumerable();
            bool IsChecked = checkedListBox2.CheckedItems.Contains(checkedListBox2.SelectedItem);
 else if (fileArr1.Equals("installer_input.txt"))
            {
                if (IsChecked && checkedListBox2.CheckedItems.Count != checkedListBox2.Items.Count)
                    inilines = inilines.Select(line => line == string.Format("#product.{0}", checkedListBox2.SelectedItem)
                                                       ? Regex.Replace(line, string.Format("#product.{0}", checkedListBox2.SelectedItem), string.Format(@"product.{0}", checkedListBox2.SelectedItem))
                                                       : line);
                else if (!IsChecked || checkedListBox2.CheckedItems.Count == checkedListBox2.Items.Count)
                    inilines = inilines.Select(line => (line == string.Format("product.{0}", checkedListBox2.SelectedItem))
                                                       ? Regex.Replace(line, string.Format(@".*product.{0}", checkedListBox2.SelectedItem), string.Format(@"#product.{0}", checkedListBox2.SelectedItem))
                                                       : line);
                if (checkedListBox2.CheckedItems.Count == checkedListBox2.Items.Count)
                    checkBox1.Checked = true;

                else
                    checkBox1.Checked = false;

                string strWrite = string.Join(Environment.NewLine, inilines.ToArray());
                File.WriteAllText(installerfilename, strWrite);

            }
        }

第二个代码是:

private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            SetAllItemsChecked(cb.Checked);

            var installerLines = ReadInstallerLines();
            SetAllProductsChecked(installerLines.ToList(), cb.Checked);
            SaveInstaller(installerLines);
        }

        private void SetAllItemsChecked(bool check)
        {
            for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
            {
                this.checkedListBox2.SetItemChecked(i, check);
            }
        }

        private IEnumerable<string> ReadInstallerLines()
        {
            var lin = (path + "config.ini").ToString();
            var lines = File.ReadAllLines(lin);
            string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
                        .Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
            string pathTemp = @"C:\temp\";
            string[] pathArr = InstallerFile.Split('\\');
            string[] fileArr = pathArr.Last().Split('\\');
            string fileArr1 = String.Join(" ", fileArr);
            string installerfilename = pathTemp + fileArr1;
            string installertext = File.ReadAllText(installerfilename);
            return File.ReadLines(pathTemp + fileArr1);
        }

        private void SetAllProductsChecked(IList<string> installerLines, bool check)
        {
            for (var i = 0; i < installerLines.Count; i++)
            {
                if (installerLines[i].Contains("product="))
                {
                    installerLines[i] = check
                        ? installerLines[i].Replace("#product", "product")
                        : installerLines[i].Replace("product", "#product");
                }
                if (installerLines[i].Contains("product."))
                {
                    installerLines[i] = check
                        ?installerLines[i].Replace("#product.", "product.")
                         : installerLines[i].Replace("product.", "#product.");
                }
            }
        }

        private void SaveInstaller(IEnumerable<string> installerLines)
        {
            var lin = (path + "config.ini").ToString();
            var lines = File.ReadAllLines(lin);
            string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
                        .Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
            string pathTemp = @"C:\temp\";
            string[] pathArr = InstallerFile.Split('\\');
            string[] fileArr = pathArr.Last().Split('\\');
            string fileArr1 = String.Join(" ", fileArr);
            string installerfilename = pathTemp + fileArr1;         
            File.WriteAllLines(installerfilename, installerLines);
        }
    }

首先,我可以检查列表中的框,但是当我尝试点击checkBox1时,我有下一个错误:The process cannot access the file 'C:\temp\installer_input.txt' because it is used by another process。 我如何使程序工作?我如何优化我的代码?

1 个答案:

答案 0 :(得分:0)

基本上单个线程/进程可以访问一个资源,在这种情况下,在一个实例中你可以做的是使用EventWaitHandle等待直到某个其他进程或线程占用了这样的文件:< / p>

EventWaitHandle waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "SHARED_BY_ALL_PROCESSES");
waitHandle.WaitOne();
/* process file*/
waitHandle.Set();