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

    public void WriteLog(string logStr)
    {
        lock (this)
        {
            string path = @"D:\log\payment\";
            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:\log\payment\2014-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:\log\payment\";
                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();
            }
        }

  

转载于:https://www.cnblogs.com/buguge/p/3978850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值