我是初學者在C#中。在我的項目中,用戶通過OpenFileDialog框選擇一個圖像文件。當他/她選擇我正在後面的代碼是這樣的映像文件:將現有文件添加到文件夾
File.Copy(SourceFilePath, DestinationFilePath);
與上面的代碼的問題是,它是當用戶試圖加入一個現有的圖像文件拋出錯誤。爲了避免這種錯誤,我改變了我的代碼以下之一:
if (File.Exists(DestinationFilePath))
{
intCount++;
File.Copy(SourceFilePath,TemporaryFilePath);
File.Copy(TemporaryFilePath, DestinationFilePath + intCount.ToString());
File.Delete(TemporaryFilePath);
}
else
{
File.Copy(SourceFilePath, DestinationFilePath);
}
在上面的代碼的問題是,它是在圖像文件的最後像image.gif1
它改變了文件中添加intCount
值延期。如何添加計數器到圖像文件路徑?
我認爲我在這裏用來檢查現有文件的方法不是正確的做法。
更新:回答: -
int intCount = 1;
while (File.Exists(Application.StartupPath + DirectoryPath + strPath))
{
strPath = Path.GetFileNameWithoutExtension(strPath) + intLarge.ToString() + Path.GetExtension(strPath);
intCount++;
}
intCount = 1;
您可以使用'Path'類來操作文件名。 – Shaamaan