如何将文件从我的目录移动到另一个目录而不会出现异常

时间:2015-05-17 05:17:02

标签: c#

它不断抛出异常:

  

Ant JSON Serializer失败:进程无法访问该文件,因为   它被另一个进程使用。

我知道有很多帖子可以修复该异常,但它不适用于我的代码。有人能指出我正确的方向吗?

static string antJsonSerializer(){
    #region  KDI SALES
    string[] allfiles = Directory.GetFiles(@"C:\xml\");

    // Put all file names in root directory into array.
    string sourceDirectory = @"C:\xml";
    string destinationDirectory = @"C:\xml\Archive";

    // Check if directories are existing
    bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
    if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);

    bool xmlArchive = System.IO.Directory.Exists(sourceDirectory);
    if (!xmlArchive) System.IO.Directory.CreateDirectory(sourceDirectory);

    AntHelpers drone = new AntHelpers();
    foreach (string name in allfiles)
    {                
        try
        {
            drone.xmltosql(@name.Trim());
            Directory.Move(sourceDirectory, destinationDirectory); //Archive
        }
        catch (Exception e)
        {
            //Console.WriteLine("Main Process Catch ERR: " + e.Message);
            //ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
            AntHelpers.ErrLogtoDB("SALES", "", "Ant JSON Serializer Failed: " + e.Message, 
                "LeafCutterLogFile_JSONSerializer_" + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");               
        }                
        //drone.ExtractSQLSendAntHill(); //For testing: OFF 
    #endregion            
    }

    return " !!!! Work Complete !!!! ";
}

3 个答案:

答案 0 :(得分:2)

试试这个:

// Ensure that the target does not exist. 
if (File.Exists(destinationPath))   
    File.Delete(destinationPath);

// Move the file.
File.Move(sourcePath, destinationPath);

有关详细信息,请参阅File.Move Method

答案 1 :(得分:1)

您当前的代码正在尝试移动整个目录 - 请尝试File.Move

string newPath = Path.Combine(destinationDirectory, Path.GetFileName(name));
File.Move(name, newPath);

答案 2 :(得分:0)

谢谢你们两个人@ C.Evenhuis& @manoj_rp。我修复了我的File.Move();它现在是File.Move(@name,“ArchivedlogName.txt”);我会投两票。