Code to check if any other process is using the file.

Code to check if any other process is using the file.


using System;
using System.Collections.Generic;
using System.Text;
//Need to add below namespace to use StreamWriter
using System.IO;

namespace CheckFile
{
class CheckFile
{
static void Main(string[] args)
{
//Call function to check the file status
CheckFile FileStatus = new CheckFile();
FileStatus.ChkFile();
}
private bool ChkFile()
{
string f = "C:\\test.txt";
bool strFileAccessChk = false;
//use StreamWriter to write into a file
StreamWriter sw = null;
FileInfo fi = new FileInfo(f);
try
{
//Append to check current status.
sw = fi.AppendText();
strFileAccessChk = true;
}
catch (Exception ex)
{
strFileAccessChk = false;
}
finally
{
if (sw != null)
{
//Close the file opened to write
sw.Close();
}
}
//Return true or false
return strFileAccessChk;
}
}
}


Attachments

Comments

Author: Asheej T K22 Nov 2009 Member Level: Gold   Points : 0

I hope this is how you are expecting the post.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: