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

    static void Main(string[] args)
            {
                Directory.CreateDirectory(@"d:ok");
                File.Create(@"d:okabc.txt");
                string str = "sve";
                FileStream fs = null;
                try
                {
                    //1、创建文件流(字节流)
                    using (fs = new FileStream(@"d:okabc.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:okabc.txt”正由另一进程使用,因此该进程无法访问该文件

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

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

  • 相关阅读:
    笔记:端子镀金厚度
    笔记:C 编译过程
    抽象类与接口类
    面向对象的三大特性之继承
    类命名空间与对象、实例的命名空间 面向对象的组合用法
    初识类和对象
    面向过程与面向对象
    初识面向对象
    hashlib模块configparser模块logging模块
    collections模块和os模块
  • 原文地址:https://www.cnblogs.com/lizhenlin/p/6434928.html
Copyright © 2011-2022 走看看