当我调用该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();
}
}
临摹微笑
相关分类