FileSystemWatcher file in use problem

C

Charlie Kunkel

I need help. I have a directory I'm watching for creation of .TIF
files, whereupon creation, I need to launch a process (command line
exe) that converts the TIF file to a postscript file. (using
tif2ps.exe) The problem is, I can't open the .TIF file as long as my
application's running! tif2ps.exe always tells me "Cannot open file".

Here's the code in my Windows C# App:

private void button1_Click(object sender, System.EventArgs e)
{
FileSystemWatcher objFSW = new FileSystemWatcher();
objFSW.Path = "c:\\BizDocs\\vault";
objFSW.Filter = "*.tif";
label1.Text = "Watching " + objFSW.Path;
//Setup Events
objFSW.Created += new FileSystemEventHandler(FileCreated);
//Start Things up
objFSW.EnableRaisingEvents = true;
}


public static void FileCreated(object source, FileSystemEventArgs e)
{

#region WAIT FOR IT TO BE DONE CREATING...
Stream stream = null;
while (true)
{
try
{
if ((stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read,
FileShare.None)) != null)
break;
}
catch (IOException ex)
{
System.Threading.Thread.Sleep( 1000 );
}
}

if ( stream == null )
throw new ApplicationException("can't open file");

#endregion WAIT FOR IT TO BE DONE CREATING...

//give the output a stream to write to
System.IO.StreamWriter sw =
new StreamWriter(e.Name.ToString().Substring(0,e.Name.ToString().Length-3)
+ "ps");

//DEFINE A NEW PROCESS
System.Diagnostics.Process procTiff2ps = new
System.Diagnostics.Process);
System.Diagnostics.ProcessStartInfo i = new
System.Diagnostics.ProcessStartInfo();

i.FileName = "tiff2ps.exe";
i.Arguments = e.FullPath.ToString();//"C:\\BizDocs\\Vault\\401.TIF";
i.RedirectStandardOutput = true;
i.CreateNoWindow = true;
i.UseShellExecute = false;
procTiff2ps.StartInfo = i;
}

Help!

//START THE PROCESS
procTiff2ps.Start();
 
T

Tom

Thats because you are opening and locking it. Why would you open the
file if the command line tool was going to open it.
 
S

Sunny

Ok, I see why OP is opening the file, to check if it is fully created.
But OP have to be sure to close it after that. The change should be:

while (true)
{
using (Stream stream = File.Open(...))
{
if (stream != null)
break;
}
Thread.Sleep(1000);
}

Sunny
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top