簡體   English   中英

該進程無法訪問該文件,因為它正在被另一個進程使用

[英]The process cannot access the file because it is being used by another process

當我從bat文件start myapp.exe .net控制台應用程序時,例如, start myapp.exe

然后,myapp.exe嘗試將文件寫入其當前目錄,盡管我收到一個.net運行時錯誤,聲稱該文件正在由另一個應用程序使用(沒有其他正在運行的文件)

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

盡管當我正常啟動但沒有批處理文件(例如,雙擊它)時,它運行正常並輸出文件。 我以為這可能與特權有關,盡管嘗試以管理員身份運行批處理文件,但出現了相同的錯誤“文件正在使用中……”。

誰能對此有所啟示?

碼:

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 + "");
        }
    }
}

從批處理文件看來,您正在將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.

在OnCreated事件完成后,嘗試進行處理。 也許啟動一個短計時器並在計時器滴答時寫入文件(記住要停止計時器)

即使尚未寫入文件,也會立即觸發創建文件的事件。 當您得到IOException時,您應該始終嘗試打開文件並稍等片刻。 您可以在此處找到解決方案: http : //bloggingabout.net/blogs/jschreuder/archive/2006/07/06/12886.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM