I have written a windows service to move a file from one location to another and,
then read the file in the new location and write the data to the database.
In the middle of the execution there is an error message:
IOException: The process cannot access the file 'file path' because it is being used by another process.
My code:
File move class
public void mysql()
{
string fileName = "Bargstedt.csv";
string sourcePath = @"\\192.168.1.2\Data\Company Files\";
string targetPath = @"C:\Users\source";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
fileName = System.IO.Path.GetFileName(fileName);
destFile = System.IO.Path.Combine(targetPath, fileName);
FileInfo info = new FileInfo(destFile);
bool exists = info.Exists;
if (exists == true)
{
try
{
int delay = 400;
File.Delete(@"C:\Users\Isuruh\source\Bargstedt.csv");
Thread.Sleep(delay);
System.IO.File.Copy(sourceFile, destFile, true);
Debug.WriteLine("file moved");
}
catch (IOException ex) { }
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Console.WriteLine("Press any key to exit.");
}
Insert Class
public void Insert()
{
if (this.OpenConnection() == true)
{
using(var reader = new StreamReader(@"C:\Users\source\Bargstedt.csv"))
//using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
List<string> listA = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
string querynew = "INSERT INTO new_jobs"
+ "(board_code,status,code,no1,no2,thickness,dimension,material,root,variable,number,stable,constant)"
+ "VALUES (?jobNo, ?strClientName, ?strClientReference, ?strJobCategory, ?datCommisioned, ?datPromisedDelivery, ?division, ?date_assigned, ?root, ?variable, ?number, ?stable, ?constant)";
I did not mention the whole code for the service since it's too lengthy.
As given in Solution 01 I tried to use,
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
line instead of
using(var reader = new StreamReader(@"C:\Users\source\Bargstedt.csv"))
But that triggers errors in the below keywords I have used.
I am not sure is it possible to use a file open instead of a reader class?
Basically, what I need to do is start the Insert process after completing the file move process.
Any suggestions on how to do that?
PS: This is possibly a duplicate question of the question I have mentioned above. I tried my very best to make this question unique. Appreciate if not marked as duplicate. Thank you!