正由另一进程使用,因此该进程无法访问该文件

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

原文地址:https://www.cnblogs.com/lizhenlin/p/6434928.html