我似乎无法访问我正在编写的程序中使用的文件。我不确定究竟是如何工作的,因为我希望我的程序打开你选择的文件,它确实如此,然后我希望它能够将信息输入到一个arrary中,然后从那里开始,将数组中的信息写入您打开的文件中。当我尝试使用某些代码开始处理它时,它告诉我,“进程无法访问文件'文件',因为它正被另一个进程使用。”这是我到目前为止所拥有的。请告诉我。谢谢。有问题的区域是代码的Save_Click部分,我写了“这是一个测试”谢谢。
public partial class ListingSearch : Form
{
string line;
DialogResult result;
string fileName;
int i = 0;
string[] first = new string[100];
string[] last = new string [100];
string[] phone = new string [100];
string[] grade = new string [100];
public ListingSearch()
{
InitializeComponent();
MessageBox.Show("Please be sure to open a file before beginning");
}
private void OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
//firstName.Text = words[4];
//lastName.Text = words[5];
//telephone.Text = words[6];
//GPA.Text = words[7];
}
Read.Enabled = true;
}
}
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllText(fileName, "This is a test");
}
private void Read_Click(object sender, EventArgs e)
{
MessageBox.Show(fileName);
MessageBox.Show(File.ReadAllText(fileName));
}
private void info_Click(object sender, EventArgs e)
{
first[i] = firstName.Text;
firstName.Text = " ";
last[i] = lastName.Text;
lastName.Text = " ";
phone[i] = telephone.Text;
telephone.Text = " ";
grade[i] = GPA.Text;
GPA.Text = " ";
i++;
}
private void displayinfo_Click(object sender, EventArgs e)
{
if (i == 0)
MessageBox.Show("Nothing to display!");
else
for (int j = 0; j < i; j++)
{
MessageBox.Show(first[j] + " " + last[j] + "\r" + phone[j] + "\r" + grade[j]);
}
}
答案 0 :(得分:2)
你在这里得到错误
File.ReadAllText(fileName)
因为你在这里打开同一个文件
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
答案 1 :(得分:1)
完成阅读后需要关闭文件。另外,不知道为什么要打开文件,因为你随后使用了File.ReadAllText
来处理文件的全部打开和关闭。
似乎您的OpenFile_click
事件应该如下所示:
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
Read.Enabled = true;
}
答案 2 :(得分:0)
您尚未关闭StreamReader。 C#将锁定文件,直到你这样做。或者,您可以在关闭StreamReader后使用StreamWriter