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

时间:2011-05-20 20:27:13

标签: c# .net windows

当我从bat文件启动我的.net控制台应用程序时,例如start myapp.exe

myapp.exe然后尝试将文件写入其当前目录,尽管我收到一个.net运行时错误,声称该文件正由另一个应用程序使用(没有其他运行)

http://i.stack.imgur.com/XLmnR.png

虽然当我正常启动时没有批处理文件,例如双击它,它运行正常,输出文件很好。我认为它可能与privilages有关,虽然尝试以管理员身份运行批处理文件,但我得到了相同的错误“文件正在使用中......”

有人能否对此有所了解?

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileSearcher
{
class Program
{    
    static void Main(string[] args)
    {
        string dirPath = "C:\\";
        FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath); 
        fileWatcher.IncludeSubdirectories = true;  
        fileWatcher.Filter = "*.exe";    
        // fileWatcher.Filter = "C:\\$Recycle.Bin";   
        //  fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);   
        fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);    
        //  fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);  
        //  fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);    
        fileWatcher.EnableRaisingEvents = true;      

        // updated code


        Console.ReadKey(); 
    }



        static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine(e.OldName + " was renamed to " + e.Name);
        }

        static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)

        {
            Console.WriteLine(e.Name + " was deleted");
        }

        static void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {

            using (StreamWriter fileWriter = new StreamWriter("process.lst", true))
            {
                var data = true;
                fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
            }


        }

        static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.Name + "");
        }
    }
}

3 个答案:

答案 0 :(得分:2)

从批处理文件看,您要将stdout(1>)发送到您在应用程序中写入的同一文件(process.lst)。 你可以做其中一个,而不是两个

例如,此应用程序在单独运行时工作正常:

static void Main(string[] args)
{
    StreamWriter writer = File.CreateText("process.lst");

    Console.WriteLine("Writing to the file.");

    writer.Write("Testing 1.2.3.4");

    Console.WriteLine("Finished.");
}

但是,从myTestApp.exe 1> process.lst这样的命令行运行会产生与您相同的异常:

The process cannot access the file 'process.lst' because it is being used by another process.

答案 1 :(得分:0)

在OnCreated事件完成后尝试执行您的过程。也许启动一个短计时器并在计时器滴答时写入文件(记得停止计时器)

答案 2 :(得分:0)

即使文件尚未写入,也会立即触发创建文件的事件。当你收到IOException时,你应该总是尝试打开文件并稍等一下。您可以在此处找到解决方案:http://bloggingabout.net/blogs/jschreuder/archive/2006/07/06/12886.aspx