[英]Move files from one folder to another C# Error File being used by another process
[英]Process xml files and move to another folder
处理完每个xml文件后,我需要将其移动到另一个文件夹。 要执行此操作的代码是什么以及将其放置在何处,请确保如果存在目标中具有相同名称的文件,则此文件将被覆盖
string Path1 = @"D:\dataIn";
string Path2 = @"D:\dataOut";
con.Open();
label1.Text = "";
foreach (string file in Directory.EnumerateFiles(Path1, "*.xml"))
{
DataSet ds = new DataSet();
ds.ReadXml(file);
DataTable dt1 = ds.Tables["Order"];
DataTable dt2 = ds.Tables["Details"];
using (SqlBulkCopy bc = new SqlBulkCopy(con))
{
bc.ColumnMappings.Add("account", "account");
bc.ColumnMappings.Add("date", "date");
bc.ColumnMappings.Add("value", "value");
bc.DestinationTableName = "header";
bc.WriteToServer(dt1);
}
using (SqlBulkCopy bc = new SqlBulkCopy(con))
{
bc.ColumnMappings.Add("itemID", "itemID");
bc.ColumnMappings.Add("qty", "qty");
bc.ColumnMappings.Add("price", "price");
bc.DestinationTableName = "items";
bc.WriteToServer(dt2);
}
}
您可能正在寻找File.Move
。
不要忘记IO名称空间:
using System.IO;
然后是移动文件的代码,您将把它放在for循环的末尾:
if (File.Exists(newFile)) // Did we find the file?
{
File.Delete(newFile); // Yep, so delete it.
}
File.Move(file, newFile); // Move the file.
您也可以使用File.Copy
,但是如果要“移动”它,则必须删除该文件。
这是您要对foreach循环执行的操作:
foreach (string file in Directory.EnumerateFiles(Path1, "*.xml"))
{
string newFile = path2 + @"\" + Path.GetFileName(file);
DataSet ds = new DataSet();
ds.ReadXml(file);
DataTable dt1 = ds.Tables["Order"];
DataTable dt2 = ds.Tables["Details"];
using (SqlBulkCopy bc = new SqlBulkCopy(con))
{
bc.ColumnMappings.Add("account", "account");
bc.ColumnMappings.Add("date", "date");
bc.ColumnMappings.Add("value", "value");
bc.DestinationTableName = "header";
bc.WriteToServer(dt1);
}
using (SqlBulkCopy bc = new SqlBulkCopy(con))
{
bc.ColumnMappings.Add("itemID", "itemID");
bc.ColumnMappings.Add("qty", "qty");
bc.ColumnMappings.Add("price", "price");
bc.DestinationTableName = "items";
bc.WriteToServer(dt2);
}
if (File.Exists(newFile)) // Did we find the file?
{
File.Delete(file); // Yep, so delete it.
}
File.Move(file, newFile);
}
File.Copy
将复制文件,并覆盖该名称的任何现有文件。 看这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.