我已经编写了Windows服务,可以将文件从一个位置移动到另一个位置,
然后在新位置读取文件并将数据写入数据库。
在执行过程中出现错误消息:
IOException:该进程无法访问文件“文件路径”,因为它正在被另一个进程使用。
我的代码:
文件移动类
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.");
}
插入课程
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)";
我没有提到服务的整个代码,因为它太长了。
我尝试使用Solution 01中给出的
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
行而不是
using(var reader = new StreamReader(@"C:\Users\source\Bargstedt.csv"))
但这会触发我使用的以下关键字中的错误。
我不确定是否可以使用打开的文件代替阅读器类?
基本上,我需要做的是在完成文件移动过程之后开始插入过程。
关于如何做到这一点的任何建议?
PS:这可能是我上面提到的问题的重复问题。我尽力使这个问题独一无二。赞赏,如果没有标记为重复。谢谢!