2016-11-29 66 views
1

我正在嘗試將DateTime印章,前綴和唯一編號添加到文件名中。我的期望的輸出是:附加文件名返回不正確的字符串

\ ParentDirectory \子目錄\另一子目錄\ Prefix-唯一號碼 - 11 29 2016 2 07 30 PM.xlsx

PrefixUnique 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

正如你在上面的輸出中看到的字符串不正確,首先我得到了一個額外的-\,並且文件擴展名也沒有通過。有人可以告訴我我要去哪裏嗎?

+3

Path.GetFullPath(fileName)返回完整路徑而不是文件名。 – AnthonyLambert

+0

@AnonyLambert哦好的,但是我怎麼會在我返回的值中得到一個額外的' - \'?另外我想返回完整路徑和附加文件,因爲稍後我將文件保存到具有新名稱的路徑 – Code

+0

您不需要'Path.Combine'只是將前綴和數字連接在一起。 'Path.Combine'用於將路徑的各個部分與適當的路徑分隔符組合在一起。 – juharr

回答

1

代碼的發佈版提供以下的輸出:

\ ParentDirectory \子目錄\另一個子目錄\ MyFile.xlsxShipping注 - 0254900 - MyFile29 11 2016 15 46 48.xlsx

,並沒有你貼:

\ ParentDirectory \子目錄\另一個子目錄\運費說明 - \ 0254900 - 11月29日2016年2 08 10 PM

,如果您想要的輸出是:

\ ParentDirectory \子目錄\另一個子目錄\ Prefix-唯一編號 - 11月29日2016年2 07 30 PM.xlsx

您需要將目錄移動到Path.Combine並使用GetDirectoryName。另外刪除行:

Path.GetFileNameWithoutExtension(fileName) 

由於所需輸出我沒有看到舊的文件名"MyFile"
此代碼:

public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber) 
{ 
    return string.Concat(    
     Path.Combine(Path.GetDirectoryName(fileName), prefix + " - " + uniqueNumber + " - "), 
     DateTime.Now.ToString() 
     .Replace(".", " ") 
     .Replace(":", " ") 
     .Trim(), 
     Path.GetExtension(fileName) 
     ); 
} 

將產生以下輸出:

\ ParentDirectory \子目錄\另一子目錄\郵費注 - 0254900 - 29 11 2016 15 39 37。XLSX

+0

我剛試過這個,它完美的工作!謝謝。我更新了這一行'.Replace(「。」,「」)'到'.Replace(「/」,「」)'' – Code

2

以下是我會做它

public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber) 
{ 
    return Path.Combine(
     Path.GetDirectoryName(fileName), 
     string.Concat(
      prefix, 
      " - ", 
      uniqueNumber, 
      " - ", 
      Path.GetFileNameWithoutExtension(fileName), 
      DateTime.Now.ToString("MM dd yyyy h mm ss tt"), 
      Path.GetExtension(fileName))); 
} 

這正確地使用Path.Combine到該目錄從Path.GetDirectoryName結合起來,你是新的連結文件名。注意我也使用日期格式字符串而不是替換。您可能需要考慮更改該格式並在文件名和日期之間加上分隔符。

相關問題