System.IO.IOException 创建文件
System.IO.IOException creating File
如果我在新创建的文件中写入内容,我会遇到错误。
这是我的代码:
private void ButtonClick(object sender, EventArgs e)
{
Button b = (Button)sender;
string inputKey = b.Text;
for (int i = 0; i < tunes.Length; i++)
{
if (b.Text == tun[i].TuneName)
{
Console.Beep(tun[i].Frequency, 200);
Input.Items.Add(b.Text);
Output.Items.Add(tun[i].TuneName);
if (startButtonPressed == true)
{
filename2 = musicFileName + ".csv";
File.WriteAllText(filename2, tun[i].TuneName);
RecordList.Items.Add(tun[i].TuneName);
}
}
}
}
错误出现在行:File.WriteAllText()...
说文件不能使用,因为它被另一个进程使用了,但是我没有打开任何文件。
您需要确保变量 filename2
包含有效路径,例如 C:\temp\myfile
而不仅仅是 myfile
此外您可能需要 运行 visual studio 如果该位置无法以其他方式访问,则具有更高的权限。
您也可以使用 streamwriter...
using (StreamWriter writer =new StreamWriter(musicFileName + ".csv";))
{
writer.Write(tun[i].TuneName);
}
我会使用 File.Create()
生成的文件流,但我会在 using 语句中进行循环,这样你就可以确保所有资源都将在最后释放(这就是为什么你使用 using
).
using (FileStream fs = File.Create(Path.Combine(musicFileName, ".csv")))
{
foreach (tun in tunes)
{
fs.Write(tun.TuneName);
}
}
您实际遇到的问题是,您从未关闭文件。您应该查找 using-keyword. It can used only with classes implementing the IDisponsable 界面。然后它将在 using
块的末尾调用 disponse()
并且所有资源将被释放,例如文件将被关闭。
如果我在新创建的文件中写入内容,我会遇到错误。
这是我的代码:
private void ButtonClick(object sender, EventArgs e)
{
Button b = (Button)sender;
string inputKey = b.Text;
for (int i = 0; i < tunes.Length; i++)
{
if (b.Text == tun[i].TuneName)
{
Console.Beep(tun[i].Frequency, 200);
Input.Items.Add(b.Text);
Output.Items.Add(tun[i].TuneName);
if (startButtonPressed == true)
{
filename2 = musicFileName + ".csv";
File.WriteAllText(filename2, tun[i].TuneName);
RecordList.Items.Add(tun[i].TuneName);
}
}
}
}
错误出现在行:File.WriteAllText()... 说文件不能使用,因为它被另一个进程使用了,但是我没有打开任何文件。
您需要确保变量 filename2
包含有效路径,例如 C:\temp\myfile
而不仅仅是 myfile
此外您可能需要 运行 visual studio 如果该位置无法以其他方式访问,则具有更高的权限。
您也可以使用 streamwriter...
using (StreamWriter writer =new StreamWriter(musicFileName + ".csv";))
{
writer.Write(tun[i].TuneName);
}
我会使用 File.Create()
生成的文件流,但我会在 using 语句中进行循环,这样你就可以确保所有资源都将在最后释放(这就是为什么你使用 using
).
using (FileStream fs = File.Create(Path.Combine(musicFileName, ".csv")))
{
foreach (tun in tunes)
{
fs.Write(tun.TuneName);
}
}
您实际遇到的问题是,您从未关闭文件。您应该查找 using-keyword. It can used only with classes implementing the IDisponsable 界面。然后它将在 using
块的末尾调用 disponse()
并且所有资源将被释放,例如文件将被关闭。