技術とか戦略とか

IT技術者が技術や戦略について書くブログです。

C#:自ユーザーのダウンロードフォルダーのパスの取得方法

C#には、WindowsOSで定められる特殊なフォルダのパスがEnumで定義されています。

Environment.SpecialFolder 列挙型 (System) | Microsoft Docs
 
自ユーザーのダウンロードフォルダの直接のパスはEnumに登録されていないのですが、ユーザーのプロファイルフォルダ(C:\Users\(自ユーザー名))のパスは登録されているので、そこを起点にダウンロードフォルダのパスを定義できます。
詳しくはサンプルコードを見てみて下さい。
 
【サンプルコード】
・Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      string filePath =
        System.Environment.GetFolderPath
          (Environment.SpecialFolder.UserProfile) +
        @"\Downloads\test.txt";
      Console.WriteLine("■ファイルパスを表示");
      Console.WriteLine(filePath);
      StreamReader sr =
        new StreamReader(filePath, Encoding.GetEncoding("UTF-8"));
      Console.WriteLine("■読み込んだファイルの文字列を表示");
      Console.WriteLine(sr.ReadLine());
      Console.ReadKey(true);
    }
  }
}
 
・test.txt
Hello World!
 
【実行結果】(ユーザー名の箇所は編集により伏せます)
■ファイルパスを表示
C:\Users\(自ユーザー名)\Downloads\test.txt
■読み込んだファイルの文字列を表示
Hello World!