2012-10-24 2 views
42

C#コードは、入力に基づいて複数のテキストファイルを生成し、フォルダに保存します。また、テキストファイルの名前が入力と同じであると仮定しています(入力には文字のみが含まれています) 2つのファイルの名前が同じ場合は、前のファイルを上書きしています。 しかし、私は両方のファイルを保持したい。ファイルがWindowsの方法で既に存在する場合、ファイルの名前を自動的に変更します。

2番目のファイル名に現在の日付時刻または乱数を追加したくありません。代わりに、私はWindowsと同じようにしたいと思います。 fisrtファイル名がAAA.txtの場合、2番目のファイル名はAAA(2).txt、3番目のファイル名はAAA(3).txt ..... N番目のファイル名はAAA(N).txtになります。

string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); 
     foreach (var item in allFiles) 
     { 
      //newFileName is the txt file which is going to be saved in the provided folder 
      if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase)) 
      { 
       // What to do here ?     
      } 
     } 

答えて

102

これは、tempFileNameでファイルが存在するかどうかをチェックし、ディレクトリに存在しない名前が見つかるまで番号を1つずつ増やします。

int count = 1; 

string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath); 
string extension = Path.GetExtension(fullPath); 
string path = Path.GetDirectoryName(fullPath); 
string newFullPath = fullPath; 

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

ファイル拡張子が間違ってしまう、ex ** C:\ file.txt ** ** C:\ file.txt(1)**などになる – flindeberg

+4

@flindeberg良いキャッチ。エラー。 – cadrell0

+4

今後の参考にしておきたいことです。チェックされているファイルが 'some name(1)some text.txt'のような名前で、ファイルがすでに存在する場合は、両方のファイルをWindows上記のコードのように、 'some name(2)some text.txt'という名前のファイルの名前を変更し、' some name(1)some text(1).txt'という名前に変更しません。 –

1

ちょうどについてどのように:それはそこにはない場合、それは、このコードのISNが(かっこ内のインデックスに新しいファイル名を取るよされていない場合

int count = 1; 
String tempFileName = newFileName; 

foreach (var item in allFiles) 
{ 
    if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase)) 
    { 
    tempFileName = String.Format("{0}({1})", newFileName, count++); 
    } 
} 

これは、元のファイル名を使用します。拡張機能を考慮していない)。新しく生成された名前 "text(001)"が使用されている場合は、有効で未使用のファイル名が見つかるまで増分します。

+2

カウントを増やす必要があります。また、 'tempFileName'は前の項目に対して再チェックされません。したがって、 'tempFileName'は既にチェックされてパスした項目に変更することができます。 – cadrell0

+0

@ cadrell0:すみません...それは計画でした!あまりにも速く入力する。 – Ian

+1

これはファイルの拡張子を考慮しません。以下に別の例を掲載しました。 – Phill

3

その他の例では、ファイル名/拡張子を考慮していません。ここで

あなたが行く:

public static string GetUniqueFilename(string fullPath) 
    { 
     if (!Path.IsPathRooted(fullPath)) 
      fullPath = Path.GetFullPath(fullPath); 
     if (File.Exists(fullPath)) 
     { 
      String filename = Path.GetFileName(fullPath); 
      String path = fullPath.Substring(0, fullPath.Length - filename.Length); 
      String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath); 
      String ext = Path.GetExtension(fullPath); 
      int n = 1; 
      do 
      { 
       fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext)); 
      } 
      while (File.Exists(fullPath)); 
     } 
     return fullPath; 
    } 
0

あなたはそれぞれのルート・ファイル名が保存された回数を維持するためにDictionary<string,int>を宣言することができます。 (AAA(1)、AAA:

var key = fileName.ToLower(); 
string newFileName; 
if(!_dictionary.ContainsKey(key)) 
{ 
    newFileName = fileName; 
    _dictionary.Add(key,0); 
} 
else 
{ 
    _dictionary[key]++; 
    newFileName = String.Format("{0}({1})", fileName, _dictionary[key]) 
} 

この方法では、あなたがそれぞれ別々のファイル名のカウンタを持っています:その後、あなたのSave方法で、ちょうどカウンターを増やし、ベースファイル名に付加2)。 BBB(1)...

0

今は問題ありません。このコードのおかげで答えをみんな..

string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); 
     string tempFileName = fileName; 
     int count = 1; 
     while (allFiles.Contains(tempFileName)) 
     { 
      tempFileName = String.Format("{0} ({1})", fileName, count++); 
     } 

     output = Path.Combine(folderPath, tempFileName); 
     string fullPath=output + ".xml"; 
0
int count= 0; 

ファイルのファイル名です

while (File.Exists(fullpathwithfilename)) //this will check for existence of file 
{ 
// below line names new file from file.xls to file1.xls 
fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls"); 

count++; 
} 
+0

あなたは 'tempno'をどこから入手していますか? – Frecklefoot

11

ファイル名は「テスト(3).TXT」であれば、それは「テストになるだろう(4).txt」となります。

public static string GetUniqueFilePath(string filepath) 
{ 
    if (File.Exists(filepath)) 
    { 
     string folder = Path.GetDirectoryName(filepath); 
     string filename = Path.GetFileNameWithoutExtension(filepath); 
     string extension = Path.GetExtension(filepath); 
     int number = 1; 

     Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+"); 

     if (regex.Success) 
     { 
      filename = regex.Groups[1].Value; 
      number = int.Parse(regex.Groups[2].Value); 
     } 

     do 
     { 
      number++; 
      filepath = Path.Combine(folder, string.Format("{0} ({1}){2}", filename, number, extension)); 
     } 
     while (File.Exists(filepath)); 
    } 

    return filepath; 
} 
1
public static string AutoRenameFilename(FileInfo file) 
    { 
     var filename = file.Name.Replace(file.Extension, string.Empty); 
     var dir = file.Directory.FullName; 
     var ext = file.Extension; 

     if (file.Exists) 
     { 
      int count = 0; 
      string added; 

      do 
      { 
       count++; 
       added = "(" + count + ")"; 
      } while (File.Exists(dir + "\\" + filename + " " + added + ext)); 

      filename += " " + added; 
     } 

     return (dir + filename + ext); 
    } 
+1

これは問題の解決策を提供するかもしれませんが、あなたのコードがどのように動作するか、あるいはそれが持つ強み/欠陥等 –

1

私は、ファイルを移動し、移動先のファイル名が既に使用されていない場合ことを確認してしまう解決策を探していました。 Windowsと同じロジックに従い、数字を追加します。重複ファイルの後ろに角括弧が付きます。

トップの答え、@ cadrell0のおかげで、私は以下のソリューションに到着助け:途中の窓にジュゼッペさんのコメントに関しては

/// <summary> 
    /// Generates full file path for a file that is to be moved to a destinationFolderDir. 
    /// 
    /// This method takes into account the possiblity of the file already existing, 
    /// and will append number surrounded with brackets to the file name. 
    /// 
    /// E.g. if D:\DestinationDir contains file name file.txt, 
    /// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt 
    /// 
    /// </summary> 
    /// <param name="destinationFolderDir">E.g. D:\DestinationDir </param> 
    /// <param name="fileToMoveFullPath">D:\Source\file.txt</param> 
    /// <returns></returns> 
    public string GetFullFilePathWithDuplicatesTakenInMind(string destinationFolderDir, string fileToMoveFullPath) 
    { 
     string destinationPathWithDuplicatesTakenInMind; 

     string fileNameWithExtension = Path.GetFileName(fileToMoveFullPath); 
     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath); 
     string fileNameExtension = Path.GetExtension(fileToMoveFullPath); 

     destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension); 

     int count = 0; 
     while (File.Exists(destinationPathWithDuplicatesTakenInMind)) 
     { 
      destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}"); 
      count = count + 1; // sorry, not a fan of the ++ operator. 
     } 

     return destinationPathWithDuplicatesTakenInMind; 
    } 
0

は、既存のインデックスを見つけバージョンに私が働いていたファイルの名前を変更、すなわち(2)をファイル名に置き換え、それに応じてウィンドウごとにファイルの名前を変更します。 sourceFileNameは有効であるとみなされ、ユーザーはこの時点までに宛先フォルダに対する書き込み権限を持っているものとみなされます。

using System.IO; 
using System.Text.RegularExpressions; 

    private void RenameDiskFileToMSUnique(string sourceFileName) 
    { 
     string destFileName = ""; 
     long n = 1; 
     // ensure the full path is qualified 
     if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); } 

     string filepath = Path.GetDirectoryName(sourceFileName); 
     string fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName); 
     string fileNameSuffix = ""; 
     string fileNameExt = Path.GetExtension(sourceFileName); 
     // if the name includes the text "(0-9)" then we have a filename, instance number and suffix 
     Regex r = new Regex(@"\(\d+\)"); 
     Match match = r.Match(fileNameWOExt); 
     if (match.Success) // the pattern (0-9) was found 
     { 
      // text after the match 
      if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix 
      { 
       fileNameSuffix = fileNameWOExt.Substring(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length)); 
       fileNameWOExt = fileNameWOExt.Substring(0, match.Index); 
      } 
      else // remove the format at the end 
      { 
       fileNameWOExt = fileNameWOExt.Substring(0, fileNameWOExt.Length - match.Length); 
      } 
      // increment the numeric in the name 
      n = Convert.ToInt64(match.Value.Substring(1, match.Length - 2)) + 1; 
     } 
     // format variation: indexed text retains the original layout, new suffixed text inserts a space! 
     do 
     { 
      if (match.Success) // the text was already indexed 
      { 
       if (fileNameSuffix.Length > 0) 
       { 
        destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt)); 
       } 
       else 
       { 
        destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt)); 
       } 
      } 
      else // we are adding a new index 
      { 
       destFileName = Path.Combine(filepath, String.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt)); 
      } 
     } 
     while (File.Exists(destFileName)); 

     File.Copy(sourceFileName, destFileName); 
    } 
関連する問題