When I start my .net console application from a bat file e.g. start myapp.exe
myapp.exe then tries to write a file to its current directory, although I get a .net runtime error claiming that the file is in use by another application (there is nothing else running)
https://i.stack.imgur.com/XLmnR.png
Although when I launch it normally with out a batch file e.g. double click on it, it functions fine and outputs the file fine. I thought it might be something to do with privilages, although tried running the batch file as an administrator and I got the same error “File is in use…”
Could anyone shed any light on this?
Code:
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 + "");
}
}
}
It looks like from your batch file that you are sending stdout (1>) to the same file (process.lst) that you are writing to within your application. You can do one or the other, not both.
For example, this application works fine when run by itself:
But, when run from the command line like
myTestApp.exe 1> process.lstyields the same exception that you have:The process cannot access the file 'process.lst' because it is being used by another process.