RadhaKrishnaKiJaya
asked on
Windows Service to delete file in C#
Hello Experts,
In a Windows Service program, I am trying to delete a file. It works fine in my machine. For example if the file is found, my program deletes it and if the file not found, I get exception. Same program when copied to production, neither the file gets deleted, not do I get any exception. I am sure it goes to delete portion of the method. Because I tested it with log4net. FYI, in development I am using Windows 7 Pro and in Production Windows Server 2008 R2. Any idea? Below is my code. Please help.
Thank you in advance.
In a Windows Service program, I am trying to delete a file. It works fine in my machine. For example if the file is found, my program deletes it and if the file not found, I get exception. Same program when copied to production, neither the file gets deleted, not do I get any exception. I am sure it goes to delete portion of the method. Because I tested it with log4net. FYI, in development I am using Windows 7 Pro and in Production Windows Server 2008 R2. Any idea? Below is my code. Please help.
Thank you in advance.
public void DeletePMTFile()
{
string fullName = System.Configuration.ConfigurationManager.AppSettings["FULL_NAME"];
string filePath = System.Configuration.ConfigurationManager.AppSettings["FILE_PATH"];
var reader = new StreamReader(fullName);
reader.Close();
FileInfo fileName = new FileInfo(fullName);
if (File.Exists(fullName))
{
try
{
Array.ForEach(Directory.GetFiles(filePath), File.Delete);
}
catch (System.IO.IOException e)
{
log.Error("DeletePMTFile: Error while deleting the file" + e.Message);
return;
}
}
else
{
log.Warn("DeletePMTFile: " + filePath.Trim() + " not found");
}
}
ASKER
The fullName contains the directory name and the file name together. The filePath contains only the directory name belongs the file. In other words fullName and filePath both have the same folder name.
Thank you!
Thank you!
ASKER
The error is Access to the path 'C:\Path\XxxPmt.txt' is denied, that's why the file is not getting deleted. Any idea how to provide the Access?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
When creating the installer for the service, you need to ensure that the service runs as the LocalSystem ServiceAccount. See this article: ServiceAccount Enumeration. Then have a look at How to: Specify the Security Context for Services. Lastly, this article should give you a good detailed overview: Walkthrough: Creating a Windows Service Application in the Component Designer
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
in Comment ID: 42297826 I did mention it was a permission issue.
while you're also checking the file existence of fullName.
are these 2 related? why you need to check the file existence of fullName?