--- lang: ja-jp breaks: true --- # `SSH.NET` を使用して ファイルのダウンロード・アップロードを行う `C#` 2024-01-01 ## csproj ```xml= <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="SSH.NET" Version="2023.0.1" /> </ItemGroup> </Project> ``` ## cs ```csharp= /// <summary> /// /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="path"></param> /// <param name="fileName"></param> private static void SftpDownloadUpload( string host, string username, string password, string path, string fileName ) { var connectionInfo = new ConnectionInfo( host: host, username: username, authenticationMethods: new PasswordAuthenticationMethod( username: username, password: password ) ); using (var client = new SftpClient(connectionInfo)) { client.Connect(); Console.WriteLine($"================================================================="); client.ListDirectory(".").ToList().ForEach(x => Console.WriteLine(x.Name)); Console.WriteLine($"================================================================="); client.ChangeDirectory(path); Console.WriteLine($"================================================================="); client.ListDirectory(".").ToList().ForEach(x => Console.WriteLine(x.Name)); Console.WriteLine($"================================================================="); // テンポラリディレクトリを作成 string text = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } // テンポラリディレクトリにダウンロードする。 FileInfo fileinfoTarget = new FileInfo( Path.Combine(tempDirectryPath, fileName) ); // バイナリモードでダウンロードする。 using ( FileStream stream = new FileStream( fileinfoTarget.FullName, FileMode.CreateNew, FileAccess.Write ) ) { client.DownloadFile( fileinfoTarget.Name, stream ); } // バイナリモードでアップロードする。 using ( FileStream stream = new( fileinfoTarget.FullName, FileMode.Open, FileAccess.Read ) ) { client.UploadFile( stream, fileinfoTarget.Name, canOverride: true ); } // テンポラリディレクトリを削除する。 if (Directory.Exists(tempDirectryPath)) { Directory.Delete(tempDirectryPath, true); } client.Disconnect(); } } ``` ###### tags: `SSH.NET` `C#` `SFTP` `SCP` `ダウンロード` `アップロード` `SSH`