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 (x86)\Microsoft\file.exe
当我调试这个程序时。错误就会发生。消息是,该进程无法访问"c:\inputdata.txt“,因为它正在被另一个进程使用。
我不明白为什么inputdata.txt位于c:\中,为什么会发生错误。
造成这个错误的原因是什么?
发布于 2018-09-12 12:47:55
使用FileStream后必须关闭它。看看这个:Closing a file after File.Create https://msdn.microsoft.com/en-us/library/aa328800(v=vs.71).aspx
发布于 2018-09-12 12:55:24
首先读取文本文件,然后更新该文件。
using (File.Open(tmp, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
/// Not right here a append txt logic
}
// Code File.AppendAllText然后在这里追加或更新逻辑here.bcz之后,如果文件已经打开,则无法写入或更新该文件。
https://stackoverflow.com/questions/52295467
复制相似问题