记一次文件错误:"The process cannot access the file 'E:\TestFileManager\1.txt' because it is being used by another process"

最开始写的:

public bool WriteInFile(string path,string words) 
        {
            //首先判断,path有没有该路径,没有 则创建
            //【0】判断路径
            if (!File.Exists(path))
            {
                File.Create(path);//如果不存在就创建
            }
            //【1】创建文件流
            FileStream fs = new FileStream(path,FileMode.Create);
            //【2】创建写入器
            StreamWriter sw = new StreamWriter(fs,Encoding.Default);
            try
            {
                //【3】以流的方式写入数据
                sw.Write(words);
                return true;
            }
            catch (Exception)
            {

                return false;
            }
            finally 
            {
                //【4】关闭写入器
                sw.Close();
                //【5】关闭 文件流
                fs.Close();
            }
            
           
        }

public bool WriteInFile(string path,string words) 
        {
            //首先判断,path有没有该路径,没有 则创建
            //【0】判断路径
            if (!File.Exists(path))
            {
                File.Create(path);//如果不存在就创建
            }
            //【1】创建文件流
            FileStream fs = new FileStream(path,FileMode.Create, FileAccess.Write, FileShare.ReadWrite);//修改后
            //【2】创建写入器
            StreamWriter sw = new StreamWriter(fs,Encoding.Default);
            try
            {
                //【3】以流的方式写入数据
                sw.Write(words);
                return true;
            }
            catch (Exception)
            {

                return false;
            }
            finally 
            {
                //【4】关闭写入器
                sw.Close();
                //【5】关闭 文件流
                fs.Close();
            }
            
           
        }

 

 

 

posted on 2022-08-01 16:48  泰坦尼克号上的活龙虾  阅读(223)  评论(0)    收藏  举报

导航