加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在文件ASP.NET C#中写入并且之后不锁定它们

发布时间:2020-12-16 06:47:42 所属栏目:asp.Net 来源:网络整理
导读:我收到此错误:进程无法访问文件(…),因为它正被另一个进程使用. 我试过用 File.WriteAllText; StreamWriter sw = new StreamWriter(myfilepath); sw.Write(mystring); sw.Close(); sw.Dispose(); ; using (FileStream fstr = File.Create(myfilepath)) { St
我收到此错误:进程无法访问文件(…),因为它正被另一个进程使用.
我试过用
File.WriteAllText;

StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();

;

using (FileStream fstr = File.Create(myfilepath))
                {
                StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();
                fstr.Close();
                }

我所要做的就是访问一个文件,在其上写,然后关闭它.我可能犯了一个愚蠢的错误,但我想了解我做错了什么以及为什么.如何确保文件已关闭,并且不再导致此错误.

到目前为止,我的答案得到了帮助:

using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
                {
                    StreamWriter sw = new StreamWriter(fstr);
                    sw.Write(mystring);
                    sw.Close();


                }

它似乎更好,因为它似乎关闭/停止我的文件的进程,如果我第二次访问该页面时尝试访问另一个文件.但是如果我第二次尝试访问同一个文件,它会再次给我错误.

解决方法

为什么不使用:

System.IO.File.WriteAllText(myfilepath,mystring");

这不应该锁定你的文件.

内部WriteAllText使用FileShare.Read并在完成写入后立即锁定.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读