2016-09-17 4 views
0

ファイルをアップロードしてからそのファイルをコピーし、別の "Converted"フォルダに移動しようとしています。ファイルがConvertedフォルダに既に存在する場合、ファイル名は増分する必要があります。私のコードには無限ループがあり、プログラムを止めるまで停止しません。ファイル名をインクリメントすると無限ループのエラーが発生するC#

など。反射Paper.docx

コード:

string myFile = fileDoc.Text; //C:\Users\Admin\Documents\ThesisSampleFolders\Original\Reflection Paper.docx 
string targetPath2 = @"C:\Users\Admin\Documents\ThesisSampleFolders\Converted"; 
string result = Path.GetFileName(myFile); 

string combinePath = System.IO.Path.Combine(targetPath2, result); 

int count = 1; 

string fileNameOnly = Path.GetFileNameWithoutExtension(combinePath); 
string extension = Path.GetExtension(combinePath); 
string path = Path.GetDirectoryName(combinePath); 
string newFullPath = combinePath; 
string tempFileName = ""; 

while (File.Exists(newFullPath)) 
{ 
    tempFileName = string.Format("{0}({1})", fileNameOnly, count++); 
    newFullPath = Path.Combine(path, tempFileName + extension); 
    File.Copy(myFile, newFullPath); 
    //break; 
} 

事は、私はbreakを入れて試してみたが、何が起こるかは、それが最初にインクリメントした後、エラーが(1)リフレクションペーパーを言って表示されていることです.docxはReflection Paper(2).docxになる必要があります。私はこれを謝罪します。私が本当に助けてくれることを願っています。手伝ってくれてどうもありがとう!

答えて

2

これは動作するはずです:

do 
{ 
    if (File.Exists(newFullPath)) // if file exists get a new file name 
    { 
     tempFileName = string.Format("{0}({1})", fileNameOnly, count++); 
     newFullPath = Path.Combine(path, tempFileName + extension); 
    } 
    else // copy with the new path 
    { 

     File.Copy(myFile, newFullPath); 

     break; 
    } 
} 
while (true); 

変更ブレーク条件とdo { } whileします。

+0

私はそれが欲しいのと同じように機能しました。どうもありがとうございます!!!!!これは大きな助けになる! –

2

whileループを壊さないようにするには欠点があります。

ファイルは、ファイルが存在する場合
  • が一時名を持つファイル
  • チェックをコピーし、一時名を作成
  • を存在するかどうかをチェック
    1. (手順3で、それをコピーしたので、はい!)

    固定コード

    bool copied = false; 
    while (!copied) 
    { 
        if(File.Exists(newFullPath)){ 
         tempFileName = string.Format("{0}({1})", fileNameOnly, count++); 
         newFullPath = Path.Combine(path, tempFileName + extension); 
         continue; 
        } 
        File.Copy(myFile, newFullPath); 
        copied = true; 
        //break; 
    } 
    
    0123など。一時名を作成します
  • +0

    ありがとうございました!!!! –

    関連する問題