File is being locked when I try to execute delete - c#

I have a service that reads an xml document from a directory(works OK), saves the data in sql (works OK) and after that I am copying the file to a FINISHED directory (works OK) and deleting the file (NOT working)from the reading directory. The PROBLEM that I have is that the file is being locked when I try to execute the DELETE. Any advise will be appreciated so I can find where the file is being locked.
static public Res GetResMn(string FileName)
XDocument root = null;
using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader oReader = new StreamReader(file, Encoding.GetEncoding("ISO-8859-1")))
{
root = XDocument.Load(oReader);
oReader.Close();
oReader.Dispose();
}
Here is the code for the copy and delete
void CopyFile(string FileToMove, string MoveLocation)
{
try
{
System.IO.File.Copy(FileToMove, MoveLocation, true);
//System.IO.File.Move(FileToMove, MoveLocation);
File.Delete(FileToMove);
}
catch (Exception e)
{
WriteLogFile("The process failed: {0} " + e.ToString());
}
}
This is the code when I get the values from the file
var myElement1 = root.Descendants(XName.Get("rnID", #"namespace.2.0")).FirstOrDefault();
if (myElement1 != null)
{
myRPr.rnID = root.Descendants(XName.Get("rnID", #"namespace.2.0")).FirstOrDefault().Value;
}
This is the error that I am getting in my logFile
{0} System.UnauthorizedAccessException: Access to the path 'C:\ReadingDirectory\FileName.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path)
at OperaWinSrvc.OperaWinSrvc.ReadFiles()
I am gettign the same kind of error when I tried the
System.IO.File.Move

Be sure you are calling .Close() on the file object prior to attempting a delete and that you have security permissions to delete from that folder as well.
Access Denied is usually a permissions problem, but can occasionally be caused by a file locking condition.

After doing multiple check ups in different places I finally found the solution to my problem. In the service installer I had the Account property set to Local Service, I change it to LocalSystem, reinstall the service and it appears to work now.

Related

How can I delete the old one while uploading a new image with c #

I want to delete old image when uploading new one with c# but I get
the process cannot access the file because it is being used by another process. error
public void DeleteExistImage(string imageName)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/" + imageName);
using (var stream = new FileStream(path, FileMode.Create))
{
stream.Dispose();
System.IO.File.Delete(path);
}
}
Try this to delete the file and then create a new file
string path = #"c:\mytext.txt";
if (File.Exists(path))
{
File.Delete(path);
}
Also, look into the thread if it solves your issue
IOException: The process cannot access the file 'file path' because it is being used by another process

Not opening IDE as Admin causes FileStream throw access to the path is denied exception

As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.
try
{
if (File.Exists(path))
{
File.Delete(path);
}
//The following line causes an exception.
using (var stream = new FileStream(path,
FileMode.CreateNew, FileAccess.Write).Encrypt())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
jsonWriter.Formatting = Formatting.Indented;
protocolJObject.WriteTo(jsonWriter);
}
}
return ReturnCodes.Success;
}
catch (UnauthorizedAccessException ex)
{
SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
returnValue = ReturnCodes.FileAccessDenied;
}
The workaround would be to not write directly to the C: drive, or any other location that requires administrative access. Depending on the purpose of the file, there are usually three candidate locations:
The temp folder, for files that you don't need to save
The AppData folder, for files that your application will need and which may be different for different users
The install location for your application
You can get these folders like:
private static void Main()
{
// Create your own file name
var fileName = "MyAppData.txt";
// Get temp path
var tempPath = Path.GetTempPath();
// Get AppData path and add a directory for your .exe
// To use Assembly.GetExecutingAssembly, you need to add: using System.Reflection
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var exeName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
var appDataForThisExe = Path.Combine(appDataFolder, exeName);
Directory.CreateDirectory(appDataForThisExe);
// Get the path where this .exe lives
var exePath = Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
// Now you can join your file name with one of the above paths
// to construct the full path to the file you want to write
var tempFile = Path.Combine(tempPath, fileName);
var appDatFile = Path.Combine(appDataForThisExe, fileName);
var exePathFile = Path.Combine(exePath, fileName);
Console.WriteLine($"Temp file path:\n {tempFile}\n");
Console.WriteLine($"AppData file path:\n {appDatFile}\n");
Console.WriteLine($"Exe location file path:\n {exePathFile}");
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Your user account doesn't have permission to write to the C:\ drive of your computer but admin does.
You can give yourself permission by right clicking on the C:\ drive in windows explorer, select properties and then the security tab and give your account write access.
Alternatively, use a better location

The process cannot access the file 'C:\PCLtoMove\print.pcl' because it is being used by another process. Windows service

I have a folder named PCLtoMove. I have applied a filewatcherSystem in this folder to move files from this folder to another folder. first time when I start windows service It works fine but from next time it gives exception-
The process cannot access the file 'C:\PCLtoMove\fileName.pcl' because it is being used by another process.
my code to move file is -
private void SavionFileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
try
{
string sourcePath = e.FullPath;
string destination = ConfigurationManager.AppSettings["destination"] + e.Name;
File.Move(sourcePath, destination);
}
catch (Exception ex)
{
this.EventLog.WriteEntry(ex.Message, EventLogEntryType.Information);
}
}
please tell me whats wrong I am doing.
I got the solution by adding following code to the above code. Its confirms that the file is completely moved or created.
FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.ReadWrite);
fs.ReadByte();
fs.Seek(0, SeekOrigin.Begin);
fs.Dispose();
File.Move(sourcePath,destination);
break;

Write on a network folder from android (Xamarin) System.UnauthorizedAccessException

I created a android app to create a stockage list by capturing code bars, the idea is to write a csv file in to a network folder, because I want the app to run as much offline as it's possible.
Currently my code looks like:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filename = Path.Combine(path, "stock.csv");
using (var streamWriter = new StreamWriter(filename, true))
using (var writer = new CsvWriter(streamWriter))
{
foreach (var item in articulos)
{
writer.WriteField(item.codbar);
writer.WriteField(item.reference);
writer.WriteField(item.quantity);
writer.NextRecord();
}
}
string path2 = #"\\Desktop-jce8pl5\csv\stock.csv";
File.Copy(filename, path2,true);
But I keep geting a System.UnauthorizedAccessException
I tried to enter directly to the file from another computer and there
is no problem.
I give full permission to "all" and "network"
I tried directly with IP I tried not to copy, just to create
string path = #"\\Desktop-jce8pl5\csv\stock.csv";
FileStream fs = null;
if (File.Exists(path))
{
fs = File.Open(path, FileMode.Append);
}
else
{
fs = File.Create(path);
}
But there is no way.
Any help?
Thanks.
As #RobertN sugested, I tried to connect with EX File Ex and detected that I was unable to, so I checked the windows 10 general configuration to shared folders and it was only enabled to auth users.
I changed that, then I start with the cifsmanager but on that moment we decided that, if the user has access to local network he will most sure have acces to internet, so I will send the file by email.

C# Why is my code throwing a io.system.directorynotfound?

Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why?
Thanks
try
{
//create path
string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
//check path exists
if (!System.IO.File.Exists(strAppData))
{
System.IO.Directory.CreateDirectory(strAppData);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
int count = dir.GetFiles().Length;
if (count > 100)
{
string[] files = System.IO.Directory.GetFiles(strAppData);
foreach (string file in files)
{
System.IO.File.Delete(file);
}
}
this.fileName = fileName;
// delete the file if it exists
if (File.Exists(fileName))
{
//delete the file
File.Delete(fileName);
}
// write the data to the file
fs = File.OpenWrite(fileName);
sWriter = new StreamWriter(fs);
sWriter.WriteLine(headerText);
sWriter.Flush();
sWriter.Close();
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?
You're checking for the existence of a directory using System.IO.File rather than System.IO.Directory. It probably works on your machine because that directory already exists, and so the check doesn't matter.
Either way, you need to remember that the file system is volatile. Rather than checking existence, try to open the resource and handle the exception when it fails.
Check that the directory exists, not the file...
Although you're checking it, and creating it if it doesn't exist. You don't know if they have privelages to create the directory. So your Directory.CreateDirectory call may well be failing too and then sub-sequently the rest of the code will fail
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
"Remarks
The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Existsl returns false. "
That is your error right there. Your validation does not ensure that the path to the file exists

Categories