当我调用Generate
函数时,它不会创建StreamWriter
对象,而是会抛出一个异常:
另一个进程使用的文件
但文件未打开,这是第一个使用它的流。
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();
}
}
答案 0 :(得分:2)
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);
}
}