zoukankan      html  css  js  c++  java
  • C#IO正由另一进程使用,因此该进程无法访问该文件

    原代码如下:

    static void Main(string[] args)
            {
                Directory.CreateDirectory(@"d:\ok");
                File.Create(@"d:\ok\abc.txt");
                string str = "sve";
                FileStream fs = null;
                try
                {
                    //1、创建文件流(字节流)
                    using (fs = new FileStream(@"d:\ok\abc.txt", FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] bytes = Encoding.Default.GetBytes(str);
                        //2、写操作
                        fs.Write(bytes, 0, bytes.Length);             
                        fs.Flush();//清空流
                        Console.WriteLine("写入成功!");
                    }             
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    //3、关闭流
                    fs.Close();
                }
            }

    上面执行会出错:文件“d:\ok\abc.txt”正由另一进程使用,因此该进程无法访问该文件

    原因:File.Create(@"d:\ok\abc.txt");这句代码会返回一个FileStream流与该文件链接,因此被占用。

    解决方法:将上面的代码改为File.Create(@"d:\ok\abc.txt").Close();即可解决

  • 相关阅读:
    小公司的10k前端工程师应该会什么?
    webService和Restful
    码农如何主动学习?
    20个Web前端开发工程师必看的国外网站
    网站主题和内容的三个类型
    HTTP慢速攻击
    Linux等待队列原理与实现
    签名你的每个 Git Commit
    浅谈 Linux 下常用 Socket 选项设置
    API接口设计,需要注意这4点
  • 原文地址:https://www.cnblogs.com/grj001/p/12223528.html
Copyright © 2011-2022 走看看