c# - 为什么我得到另一个进程错误使用的文件?
问题描述
当我调用该Generate
函数时,它不会创建StreamWriter
对象,而是抛出一个异常:
另一个进程使用的文件
但文件未打开,这是第一个使用它的 Stream。
public static string GetWindowsUserName()
{
string st = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
bool Condition = false;
foreach (char ch in st)
{
if (ch == '\\')
Condition = true;
}
if (Condition)
{
string[] stArr = st.Split('\\');
st = stArr[stArr.Length - 1];
}
return st;
}
public static void Generate(bool Desktop, bool RemoveLast, bool InExistingTxt, int Count, int Length)
{
Random Generator = new Random();
if (Desktop)
path = $"C:\\Users\\{GetWindowsUserName()}\\Desktop\\GeneratedNumbers.txt";
else
path = "GeneratedNumbers.txt";
if (!InExistingTxt && !RemoveLast)
File.Create(path);
else if (!InExistingTxt && RemoveLast)
{
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path);
}
System.Threading.Thread.Sleep(1000);
if (File.Exists(path))
{
StreamWriter SW = new StreamWriter(path);
for (int i = 0; i < Count; i++)
{
string st = "";
for (int j = 0; j < Length; j++)
{
int o = Generator.Next(0, 11);
st += Convert.ToString(o);
}
SW.WriteLine(st);
}
SW.Dispose();
}
}
解决方案
File.Create
将流返回到创建的文件。由于您没有处理流,因此在尝试重新打开同一个文件时会出错。
我还怀疑您搞砸了“RemoveLast”逻辑。我假设您想在设置为 false 时将内容附加到现有文件:
if (InExistingTxt && !File.Exists(path))
return;
StreamWriter SW;
if (RemoveLast)
SW = File.CreateText(path);
else
SW = File.AppendText(path);
using (SW)
{
for (int i = 0; i < Count; i++)
{
string st = "";
for (int j = 0; j < Length; j++)
{
int o = Generator.Next(0, 11);
st += Convert.ToString(o);
}
SW.WriteLine(st);
}
}
推荐阅读
- python - 根据用户输入,获取另一列的排名值
- php - 如何在下拉更改中将 id 名称传递给 jquery?
- ios - iPhone XS 最大 | 斯威夫特 4.2 | 应用程序崩溃 libsystem_kernel.dylib abort_with_payload_wrapper_internal + 104
- javascript - 单击保存按钮后重定向用户
- r - 将 NA 更改为另一列中字符串的一部分
- node.js - 如何避免输入与用户输入的相同的值?
- wpf - 按下按钮时WPF失去焦点不会触发
- aframe - 如何将激光的点击绑定到拇指左键?寻求解决激光点击和传送之间的冲突
- vue.js - v-for 循环遍历基于选择器的外部数组
- xcode - 从不同的 ViewController 访问信息