簡體   English   中英

如何在沒有異常的情況下將文件從目錄移動到另一個目錄

[英]How can I move my files from my directory to another directory without getting an exception

它總是拋出異常:

Ant JSON序列化程序失敗:該進程無法訪問該文件,因為該文件正在被另一個進程使用。

我知道有很多帖子可以解決該異常,但是它不適用於我的代碼。 誰能指出我正確的方向?

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 !!!! ";
}

試試這個:

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

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

有關更多詳細信息,請參考File.Move方法

您當前的代碼正在嘗試移動整個目錄-嘗試使用File.Move

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

謝謝@ C.Evenhuis和@manoj_rp。 我修復了File.Move(); 現在是File.Move(@name,“ ArchivedlogName.txt”); 我都投票。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM