2010-07-21 69 views
0

我已經使用這個保存我的文件保存文件具有相同的名稱

string m_strDate = DateTime.Now.ToString("MM/dd/yyyy"); 
m_strDate = m_strDate.Replace("/", ""); 
strPath += "/FileHeader_" + m_strDate + ".txt"; 

所以按照這個,我每天可以省下一個文件。但是如果我再創建一次,那個文本文件中的數據就會被新的數據取代。現在,我需要的是我想帶日期和數量一起保存我的文件的一些名稱,如

"/FileHeader_1" + m_strDate + ".txt" 

等。

+0

如果您不需要時,使用'DateTime.Today.ToString()' - 這是有點快了 – abatishchev 2010-07-21 11:44:34

+0

你有問題嗎? – leppie 2010-07-21 11:44:36

+0

另外不要忘了'System.IO.Path.Combine()'結合目錄名和文件名,而不用擔心中間的斜槓等。 – abatishchev 2010-07-21 11:45:36

回答

1
string fileName = "/FileHeader_" + m_strDate + ".txt"; 
if (File.Exists(fileName)) 
{ 
    int index = 1; 
    fileName = "/FileHeader_" + index + m_strDate + ".txt"; 
    while (File.Exists(fileName)) 
    fileName = "/FileHeader_" + ++index + m_strDate + ".txt"; 
} 
2
strPath = "/FileHeader_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; 

或檢查文件是否存在:

strPath = "/FileHeader_{0}" + DateTime.Now.ToString("MMddyyyy") + ".txt"; 
if (File.Exists(string.format(strPath, "")){ 
    int i = 1; 
    while(File.Exists(string.format(strPath, i)){ i++ ; } 
    strPath = string.Format(strPath, i); 
} 
else { 
    strPath = string.format(strPath, ""); 
} 
0
string head = Path.Combine(strPath, "FileHeader_"); 
string tail = DateTime.Now.ToString("MMddyyyy") + ".txt"; 

int index = 1; 
string fileName = head + tail; 

while (File.Exists(fileName)) 
{ 
    fileName = head + index + tail; 
    index++; 
}