を作成すると、出力ファイルが既に存在するというメッセージが表示されず、しかし、それは、ファイル名の末尾に(1)を使用して新しいファイルを作成します...既存のファイルと同じ名前の新しいファイルを作成すると、Windows環境およびいくつかのアプリケーションで「新規ファイルWindows」の動作
name.doc
が
name(1).doc
私はC#で同じ動作を作成しようとしていると、私の質問があるだろう...このコードをすべて減らすことはできますか?
FileInfo finfo = new FileInfo(fullOutputPath);
if (finfo.Exists)
{
int iFile = 0;
bool exitCreatingFile = false;
while (!exitCreatingFile)
{
iFile++;
if (fullOutputPath.Contains("(" + (iFile - 1) + ")."))
fullOutputPath = fullOutputPath.Replace(
"(" + (iFile - 1) + ").",
"(" + iFile + ")."); // (1) --> (2)
else
fullOutputPath = fullOutputPath.Replace(
Path.GetFileNameWithoutExtension(finfo.Name),
Path.GetFileNameWithoutExtension(finfo.Name) + "(" + iFile + ")"); // name.doc --> name(1).doc
finfo = new FileInfo(fullOutputPath);
if (!finfo.Exists)
exitCreatingFile = true;
}
}
多くのクリーナー:)ありがとう – balexandre
当然、元の方法よりも優れています。 FileInfoオブジェクトから利用できるので、名前を別々に保存する必要はありません。 –
元のコードが具体的にインプレースでそれを更新していたので、 'fullOutputPath'が引き続き使用されるかどうかはわかりませんでした。 – jerryjvl