C#(正確に書くと.Net)では、以下のように、WindowsOSで定められる特殊なフォルダのパスがEnumで定義されています。
https://learn.microsoft.com/ja-jp/dotnet/api/system.environment.specialfolder?view=net-8.0&viewFallbackFrom=windowsdesktop-8.0
自ユーザーのダウンロードフォルダの直接のパスは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);
}
}
}
【用意するファイル】
・C:\Users\(自ユーザー名)\Downloads\test.txt
Hello World!
【実行結果】
■ファイルパスを表示
C:\Users\(自ユーザー名)\Downloads\test.txt
■読み込んだファイルの文字列を表示
Hello World!
今回はちょっとした小ネタの紹介でした。
ダウンロードしたファイルに対して加工を行うツールを作る際に便利だと思います。


コメント