2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でサクッと1行で現在日時をファイル出力する方法 (主にデバッグ用)

Last updated at Posted at 2022-01-27

C# 6.0以降 (Visual Studio 2017 なら C# 7.0 ~ 7.3 らしい)

hoge1.cs
File.AppendAllText(@"C:\hoge.txt", $"{DateTime.Now:F}\n");

現在のコンテキストに '*' という名前が存在しません。といったエラーが出たら、カーソルを合わせて、Alt+Enter (Ctrl+.)で、usingを自動追加してもらったらよいです。

それすらも面倒な人はこちら。

hoge2.cs
System.IO.File.AppendAllText(@"C:\hoge.txt", $"{System.DateTime.Now:F}\n");

備考

  • 2022年1月23日 12:34:56といった感じに追記出力されます(末尾改行付き)。別のフォーマットで出したい人は、参考のリンク先を見てください。
  • 追記ではなく上書きしたいなら、AppendAllText() → WriteAllText()
  • 改行不要なら、末尾の\nを削除
  • 他の情報も付与したければ、{}の外に記載
  • {}を複数使えば別の場所に変数埋め込んだりできます。例:(int num; が既にあるものとして`$"{num}: {DateTime.Now:F}\n"*
  • \ではなく\\でディレクトリを書きたいなら@を削除(@はエスケープシーケンスを利用しないための接頭)

参考

日付や時刻を文字列に変換するには?:.NET TIPS - @IT
https://atmarkit.itmedia.co.jp/ait/articles/0408/27/news104.html

C#で簡単にファイル入出力 - Qiita
https://qiita.com/t_sato310/items/6c6ec79f4487a52b6b9e

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?