亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我得到另一個進程錯誤使用的文件?

為什么我得到另一個進程錯誤使用的文件?

C#
牛魔王的故事 2022-12-24 09:47:55
當我調用該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();        }    }
查看完整描述

1 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超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);

    }

}


查看完整回答
反對 回復 2022-12-24
  • 1 回答
  • 0 關注
  • 108 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號