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();即可解决

  • 相关阅读:
    用 Python、 RabbitMQ 和 Nameko 实现微服务
    自定义Docker容器的 hostname
    ubuntu下升级R版本
    pair correlation ggpair ggmatrix
    RabbitMQ消息队列(一): Detailed Introduction 详细介绍
    ng-controller event data
    node项目换了环境node_modules各种报错
    Blast本地化
    angularjs $q、$http 处理多个异步请求
    解决angular页面值闪现问题
  • 原文地址:https://www.cnblogs.com/grj001/p/12223528.html
Copyright © 2011-2022 走看看