我正在嘗試將DateTime
印章,前綴和唯一編號添加到文件名中。我的期望的輸出是:附加文件名返回不正確的字符串
\ ParentDirectory \子目錄\另一子目錄\ Prefix-唯一號碼 - 11 29 2016 2 07 30 PM.xlsx
Prefix
和Unique Number
以上將被傳遞到功能。我使用下面的方法來實現這一點:
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.GetFullPath(fileName),
Path.Combine(prefix + " - " + uniqueNumber + " - "),
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString()
.Replace("/", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}
我調用上述方法爲:
string fileName = @"\\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsx";
string adjustedFileName = fileName.AppendDateTimeToFileName("Shipping Note", "0254900");
我接收的輸出如下所示:
\ ParentDirectory \子目錄\另一個子目錄\裝運注 - \ 0254900 - 11 29 2016 2 08 10 PM
正如你在上面的輸出中看到的字符串不正確,首先我得到了一個額外的-\
,並且文件擴展名也沒有通過。有人可以告訴我我要去哪裏嗎?
Path.GetFullPath(fileName)返回完整路徑而不是文件名。 – AnthonyLambert
@AnonyLambert哦好的,但是我怎麼會在我返回的值中得到一個額外的' - \'?另外我想返回完整路徑和附加文件,因爲稍後我將文件保存到具有新名稱的路徑 – Code
您不需要'Path.Combine'只是將前綴和數字連接在一起。 'Path.Combine'用於將路徑的各個部分與適當的路徑分隔符組合在一起。 – juharr