Differences

This shows you the differences between the selected revisions of the page.

2016-08-12 2016-09-29
newer .net frameworks (martin) Embedding WinSCP Executable as Resource (martin)
Line 79: Line 79:
When deploying the assembly, make sure that WinSCP executable (''winscp.exe'') is deployed along with the assembly on the target system and that WinSCP assembly [[#installing|can find the executable]]. When deploying the assembly, make sure that WinSCP executable (''winscp.exe'') is deployed along with the assembly on the target system and that WinSCP assembly [[#installing|can find the executable]].
 +===== [[resource]] Embedding WinSCP Executable as Resource =====
 +
 +If you want to avoid having the ''winscp.exe'' as a separate file (e.g. when whole your project is a single ''.exe'' file and you do not want to have any dependency), you can embed the ''winscp.exe'' as a resource to your own executable.
 +
 +Add the ''winscp.exe'' to your Visual Studio project, if not added already (e.g. by the [[#nuget|WinSCP NuGet package]]). Change file property //Build Action// to the //Embedded Resource//. If the ''winscp.exe'' was added by the NuGet package, reset the property //Copy to Output Directory// back to the //Do not copy//.
 +
 +Now, before you open a session, extract the ''winscp.exe'' from resources to a temporary file using a code like:
 +
 +<code csharp>
 +// Generate random, yet meaningful name of the temporary file
 +string tempName = Path.GetTempFileName();
 +string executableName = "WinSCP." + Path.ChangeExtension(Path.GetFileName(tempName), "exe");
 +string executablePath = Path.Combine(Path.GetDirectoryName(tempName), executableName);
 +File.Delete(tempName);
 +
 +// Extract the resource to the temporary file
 +Assembly executingAssembly = Assembly.GetExecutingAssembly();
 +string resourceName = executingAssembly.GetName().Name + "." + "WinSCP.exe";
 +
 +using (Stream resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
 +using (Stream file = new FileStream(executablePath, FileMode.Create, FileAccess.Write))
 +{
 +    resource.CopyTo(file);
 +}
 +
 +try
 +{
 +    using (Session session = new Session())
 +    {
 +        // Use the temporarily extracted executable
 +        session.ExecutablePath = executablePath;
 +
 +        // Connect
 +        session.Open(sessionOptions);
 +
 +        // Your code
 +    }
 +}
 +finally
 +{
 +    // Clean up
 +    File.Delete(executablePath);
 +}
 +</code>

Last modified: by martin