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

        public void WriteLog(string logStr)
        {
            lock (this)
            {
                string path = @"D:logpayment";
                string file = DateTime.Now.ToString("yyyy-MM-dd") + "paymentlog.ini";
                DirectoryInfo d = new DirectoryInfo(path);
                if (!d.Exists)
                {
                    Directory.CreateDirectory(path);
                }
                file = path + "\" + file;
                if (!File.Exists(file))
                {
                    File.CreateText(file);
                }
    
                StreamWriter sw = new StreamWriter(file, true);
                sw.WriteLine(DateTime.Now.ToShortTimeString() + logStr);
                sw.Flush();//防止缓存溢出    
                sw.Close();
            }
        }
    

      当文件不存在时,执行上面程序会抛出异常“System.IO.IOException: 文件“D:logpayment2014-09-18paymentlog.ini”正由另一进程使用,因此该进程无法访问此文件。

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

    解决方法:将上面的代码改为File.Create(file).Close();   或者直接将返回的FileStream赋值给下面的StreamWriter对象sw。 修改后的代码为:

            public void WriteLog(string logStr)
            {
                lock (this)
                {
                    StreamWriter sw = null;
    
                    string path = @"D:logpayment";
                    string file = DateTime.Now.ToString("yyyy-MM-dd") + "paymentlog.ini";
                    DirectoryInfo d = new DirectoryInfo(path);
                    if (!d.Exists)
                    {
                        Directory.CreateDirectory(path);
                    }
                    file = path + "\" + file;
                    if (!File.Exists(file))
                    {
                        sw = File.CreateText(file);
                    }
                    else
                    {
                        sw = new StreamWriter(file, true);
                    }
                    sw.WriteLine(DateTime.Now.ToShortTimeString() + logStr);
                    sw.Flush();//防止缓存溢出    
                    sw.Close();
                }
            }
    

      

  • 相关阅读:
    Live2d网页看板娘
    阿里云服务器(云主机)搭建网站攻略 最新9.5一个月
    Cookie小案例
    Node搭建多人聊天室
    JS鼠标点击爱心,文字特效
    JQ根据鼠标上下移动设置导航浮窗
    JS背景网页樱花特效
    Node中怎么保持MySql一直连接不断开
    Navicat for MySQL破解版
    Windows Server 2008 R2 安装MySql,PHP
  • 原文地址:https://www.cnblogs.com/buguge/p/3978850.html
Copyright © 2011-2022 走看看