当我从一个bat文件启动我的.net控制台应用程序,例如start myapp.exe
myapp.exe然后尝试写入一个文件到它的当前目录,虽然我得到一个.net运行时错误,声称该文件正在被另一个应用程序使用(没有别的运行)
http://img.zgserver.com/c%23/XLmnR.png
虽然当我通常用一个batch file启动它,例如双击它,它运行良好,并输出文件罚款。 我认为这可能是与privilages做,尽pipe尝试运行batch file作为pipe理员,我得到了同样的错误“文件正在使用…”
任何人都可以解释这一点吗?
码:
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 + ""); } } }
它看起来像从你的批处理文件,你正在发送标准输出(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