2017-04-08 38 views
0

運行下面的代碼,看到有一個名爲桌面上的文本文件MyLogFile 08.04.2017StreamWriter的文本文件名必須包括小時,分鐘和秒

Dim Log As System.IO.StreamWriter 
    Log = My.Computer.FileSystem.OpenTextFileWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\MyLogFile " & System.DateTime.Now.Date.ToString("dd/MM/yyyy") & ".txt", False) 
    Log.WriteLine("Hello") 
    Log.Close() 

我本來想更改文件名從MyLogFile 08.04.2017MyLogFile 08.04.2017 07:50:59,但它是不可能的,因爲:是不允許的。

感謝您的支持,現在我想將文件名從MyLogFile 08.04.2017更改爲MyLogFile 08.04.2017 07.50.59

回答

0

你可以這樣做:

Dim Folder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) 
Dim FileName As String = "MyLogFile " & DateTime.Now.ToString("dd.MM.yyyy HH.mm.ss") & ".txt" 
Dim Log As System.IO.StreamWriter 
Log = My.Computer.FileSystem.OpenTextFileWriter(System.IO.Path.Combine(Folder, FileName), False) 
Log.WriteLine("Hello") 
Log.Close() 
+0

如果我運行此代碼早晨小時的節目'07'。如果我運行這個代碼晚上小時再次顯示'07'。但我想要'07'早上,'19'晚上。可能? –

+0

是,改變'hh'到'HH'。參見[自定義日期和時間格式字符串(https://docs.microsoft.com/en-us/dotnet/articles/standard/base-types/custom-date-and-time-format-strings?view=netframework- 4.7)瞭解更多細節。 –

+0

非常感謝你。 –

3

我會強烈建議,包括在文件和文件夾名稱日期和時間,您從最顯著去至少顯著。原因是那麼按字母順序和時間順序匹配。就個人而言,我不使用分離器在所有所以這將是:

Log = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
                  String.Format("MyLogFile.{0:yyyyMMddHHmmss}.txt", 
                      Date.Now), 
               False) 

如果你真的想這樣做,你的方式那麼這將是:

Log = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
                  String.Format("MyLogFile {0:dd.MM.yyyy HH.mm.ss}.txt", 
                      Date.Now), 
               False) 

您只需更改格式說明作爲需要。