Can we unzip file in FTP server using C# - c#

Can I extract the ZIP file in FTP and place this extracted file on the same location using C#?

It's not possible.
There's no API in the FTP protocol to un-ZIP a file on a server.
Though, it's not uncommon that one, in addition to an FTP access, have also an SSH access. If that's the case, you can connect with the SSH and execute the unzip shell command (or similar) on the server to decompress the files.
See C# send a simple SSH command.
If you need, you can then download the extracted files using the FTP protocol (Though if you have the SSH access, you will also have an SFTP access. Then, use the SFTP instead of the FTP.).
Some (very few) FTP servers offer an API to execute an arbitrary shell (or other) commands using the SITE EXEC command (or similar). But that's really very rare. You can use this API the same way as the SSH above.
If you want to download and unzip the file locally, you can do it in-memory, without storing the ZIP file to physical (temporary) file. For an example, see How to import data from a ZIP file stored on FTP server to database in C#.

Download via FTP to MemoryStream, then you can unzip, example shows how to get stream, just change to MemoryStream and unzip. Example doesn't use MemoryStream but if you are familiar with streams it should be trivial to modify these two examples to work for you.
example from: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-download-files-with-ftp
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}
decompress stream, example from: https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
using (FileStream zipToOpen = new FileStream(#"c:\users\exampleuser\release.zip", FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
writer.WriteLine("Information about this package.");
writer.WriteLine("========================");
}
}
}
}
}
}
here is a working example of downloading zip file from ftp, decompressing that zip file and then uploading the compressed files back to the same ftp directory
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string location = #"ftp://localhost";
byte[] buffer = null;
using (MemoryStream ms = new MemoryStream())
{
FtpWebRequest fwrDownload = (FtpWebRequest)WebRequest.Create($"{location}/test.zip");
fwrDownload.Method = WebRequestMethods.Ftp.DownloadFile;
fwrDownload.Credentials = new NetworkCredential("anonymous", "janeDoe#contoso.com");
using (FtpWebResponse response = (FtpWebResponse)fwrDownload.GetResponse())
using (Stream stream = response.GetResponseStream())
{
//zipped data stream
//https://stackoverflow.com/a/4924357
byte[] buf = new byte[1024];
int byteCount;
do
{
byteCount = stream.Read(buf, 0, buf.Length);
ms.Write(buf, 0, byteCount);
} while (byteCount > 0);
//ms.Seek(0, SeekOrigin.Begin);
buffer = ms.ToArray();
}
}
//include System.IO.Compression AND System.IO.Compression.FileSystem assemblies
using (MemoryStream ms = new MemoryStream(buffer))
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Update))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
FtpWebRequest fwrUpload = (FtpWebRequest)WebRequest.Create($"{location}/{entry.FullName}");
fwrUpload.Method = WebRequestMethods.Ftp.UploadFile;
fwrUpload.Credentials = new NetworkCredential("anonymous", "janeDoe#contoso.com");
byte[] fileContents = null;
using (StreamReader sr = new StreamReader(entry.Open()))
{
fileContents = Encoding.UTF8.GetBytes(sr.ReadToEnd());
}
if (fileContents != null)
{
fwrUpload.ContentLength = fileContents.Length;
try
{
using (Stream requestStream = fwrUpload.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
}
catch(WebException e)
{
string status = ((FtpWebResponse)e.Response).StatusDescription;
}
}
}
}
}
}
}

If you're trying to unzip the files in place after they have been ftp uploaded, you will need to run a server side script with proper permissions that can be fired from within your c# application, or c# ssh as already described earlier.

Related

How to upload a file from a MemoryStream to an FTP server

I created a simple application that collects form data, generates an XML in memory as a MemoryStream object, and and delivers the XML to a server using SMB. The delivery method is simple for SMB:
var outputFile = new FileStream($#"{serverPath}\{filename}.xml", FileMode.Create);
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = stream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
outputFile.Write(buffer, 0, bytesRead);
bytesRead = stream.Read(buffer, 0, Length);
}
However, I need to create an alternative delivery method using FTP (with credentials). I don't want to rewrite my XML method, as creating it in memory saves writing to disk which has been a problem in our environment in the past.
I have not been able to find any examples that explain (for a person of very limited coding ability) how such a thing may be accomplished.
Generally when I have need to upload a file to an FTP server, I use something like this:
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("user", "pass");
client.UploadFile(uri, WebRequestMethods.Ftp.UploadFile, filename.xml);
}
Can this be adapted to upload from a MemoryStream instead of a file on disk?
If not, what other way could I upload a MemoryStream to an FTP server?
Either use FtpWebRequest, as you can see in Upload a streamable in-memory document (.docx) to FTP with C#?:
WebRequest request =
WebRequest.Create("ftp://ftp.example.com/remote/path/filename.xml");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
using (Stream ftpStream = request.GetRequestStream())
{
memoryStream.CopyTo(ftpStream);
}
or use WebClient.OpenWrite (as you can also see in the answer by #Neptune):
using (var webClient = new WebClient())
{
const string url = "ftp://ftp.example.com/remote/path/filename.xml";
using (Stream uploadStream = client.OpenWrite(url))
{
memoryStream.CopyTo(uploadStream);
}
}
Equivalently, your existing FileStream code can be simplified to:
using (var outputFile = File.Create($#"{serverPath}\{filename}.xml"))
{
stream.CopyTo(outputFile);
}
Though obviously, even better would be to avoid the intermediate MemoryStream and write the XML directly to FileStream and WebRequest.GetRequestStream (using their common Stream interface).
You can use the methods OpenWrite/OpenWriteAsync to get a stream that you can write to from any source (stream/array/...etc.)
Here is an example using OpenWrite to write from a MemoryStream:
var sourceStream = new MemoryStream();
// Populate your stream with data ...
using (var webClient = new WebClient())
{
using (Stream uploadStream = client.OpenWrite(uploadUrl))
{
sourceStream.CopyTo(uploadStream);
}
}

Broken archive after receiving by FTP C#

I try to send by FTP one .zip file. First I take one .txt file and added to archive .zip.
When I try to send this file everything is OK. But when a file is coming on the machine and I want to uncompress the .zip file is broken.
On the sender machine .zip file is OK. Only on the ftp machine is broken.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace SEND_Plovdiv
{
public class WebRequestGetExample
{
public static void Main()
{
string[] lineOfContents = File.ReadAllLines(#"C:\\M\send.txt");
string username = "";
string password = "";
foreach (var line in lineOfContents)
{
string[] tokens = line.Split(',');
string user = tokens[0];
string pass = tokens[1];
username = user;
password = pass;
}
string pathFile = #"C:\M\Telegrami\";
string zipPath = #"C:\M\Plovdiv.zip";
if (File.Exists(zipPath))
{
File.Delete(zipPath);
}
ZipFile.CreateFromDirectory(pathFile, zipPath, CompressionLevel.Fastest, false);
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://199.199.199.199/Plovdiv.zip");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(username, password);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"C:\M\Plovdiv.zip");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
Console.ReadKey();
response.Close();
}
}
}
I dont know what exactly do this part of code:
StreamReader sourceStream = new StreamReader(#"C:\M\Plovdiv.zip");
Switch from using the StreamReader to BinaryReader. Zip files are binary files not UTF8.
Here's a sample:
using (FileStream fs = File.Open(#"c:\1.bin",FileMode.Open))
{
byte[] data = new BinaryReader(fs).ReadBytes((int)fs.Length);
Encoding.getstring....
}
StreamReader vs BinaryReader?

Send a zip file as it is being created

On my website, when a user clicks a certain button, a bunch of files have to be archived in a zip and sent out. The files themselves are generated by a third part and I only have the URLs.
I have partly succeeded in that, but I have some issues.
First, if there are a lot of files to zip, the server response is slow as it first builds the zip file, then sends it. It can even crash after a while (notably, I get the error "Overflow or underflow in the arithmetic operation.").
Second, right now the file only gets sent once the zip archive is complete. I would like the download to begin immediately instead. That is to say, as soon as the user has clicked "save" from the dialog, data begins sending and it keeps sending as the zip file is being created "on the fly". I have seen that feature on some websites, for example : http://download.muuto.com/
Problem is, I can't figure out how to do that.
I have used parts of code from this question : Creating a dynamic zip of a bunch of URLs on the fly
And from this blog post : http://dejanstojanovic.net/aspnet/2015/march/generate-zip-file-on-the-fly-in-aspnet-mvc-application/
The zip file itself is created and returned in an ASP.NET MVC Controller method. Here is my code :
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace MyProject.Controllers
{
public class MyController : Controller
{
public ActionResult DownloadFiles()
{
var files = SomeFunction();
byte[] buffer = new byte[4096];
var baseOutputStream = new MemoryStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(baseOutputStream);
zipOutputStream.SetLevel(0); //0-9, 9 being the highest level of compression
zipOutputStream.UseZip64 = UseZip64.Off;
zipOutputStream.IsStreamOwner = false;
foreach (var file in files)
{
using (WebClient wc = new WebClient())
{
// We open the download stream of the file
using (Stream wcStream = wc.OpenRead(file.Url))
{
ZipEntry entry = new ZipEntry(ZipEntry.CleanName(file.FileName));
zipOutputStream.PutNextEntry(entry);
// As we read the stream, we add its content to the new zip entry
int count = wcStream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
zipOutputStream.Write(buffer, 0, count);
count = wcStream.Read(buffer, 0, buffer.Length);
if (!Response.IsClientConnected)
{
break;
}
}
}
}
}
zipOutputStream.Finish();
zipOutputStream.Close();
// Set position to 0 so that cient start reading of the stream from the begining
baseOutputStream.Position = 0;
// Set custom headers to force browser to download the file instad of trying to open it
return new FileStreamResult(baseOutputStream, "application/x-zip-compressed")
{
FileDownloadName = "Archive.zip"
};
}
}
}
Ok by fiddling a bit with the response outputstream and buffering, I've arrived to a solution :
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace MyProject.Controllers
{
public class MyController : Controller
{
public ActionResult DownloadFiles()
{
var files = SomeFunction();
// Disable Buffer Output to start the download immediately
Response.BufferOutput = false;
// Set custom headers to force browser to download the file instad of trying to open it
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("content-disposition", "attachment; filename=Archive.zip");
byte[] buffer = new byte[4096];
ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream);
zipOutputStream.SetLevel(0); // No compression
zipOutputStream.UseZip64 = UseZip64.Off;
zipOutputStream.IsStreamOwner = false;
try
{
foreach (var file in files)
{
using (WebClient wc = new WebClient())
{
// We open the download stream of the image
using (Stream wcStream = wc.OpenRead(file.Url))
{
ZipEntry entry = new ZipEntry(ZipEntry.CleanName(file.FileName));
zipOutputStream.PutNextEntry(entry);
// As we read the stream, we add its content to the new zip entry
int count = wcStream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
zipOutputStream.Write(buffer, 0, count);
count = wcStream.Read(buffer, 0, buffer.Length);
if (!Response.IsClientConnected)
{
break;
}
}
}
}
}
}
finally
{
zipOutputStream.Finish();
zipOutputStream.Close();
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
}

Download zip file from the server and parsing it

I am trying to download a zipped file from the server and trying to show the content of each files in zipped folder to the view.
I wrote a separate code where the file is on my laptop and I ran across each file and dislpayed the content such as
static void Main(string[] args)
{
string filePath = "C:\\ACL Data\\New folder\\files.zip";
var zip= new ZipInputStream(File.OpenRead(filePath));
var filestream=new FileStream(filePath,FileMode.Open,FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
Console.WriteLine(item.Name);
using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
{
Console.WriteLine(s.ReadToEnd());
}
}
Console.Read();
}
I am using sharplibzip library to implement this
This is the case when the zip file is located locally in the system. My next task scenario is what if the zipped file is located on the server. I am figuring out the way to implement it, below is the code what I assume should work
static void Main(string[] args)
{
string url = "https://test/code/304fd9c6-7e53-42a2-845a-624608bfd2ce.zip";
WebRequest webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
WebResponse webResponse = webRequest.GetResponse();
var zip = new ZipInputStream(webResponse.GetResponseStream());
ZipEntry item1;
//var zip= new ZipInputStream(File.OpenRead(filePath));
var filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
Console.WriteLine(item.Name);
using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
{
Console.WriteLine(s.ReadToEnd());
}
}
Console.Read();
}
I am stuck at this part: var filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
This expect the first parameter to be path of the zip file. Since in the new scenario zip file is located remotely on the server. What should be the parameter in this case?
Your original code opens the stream twice on the following rows, which I think is causing some confusion:
var zip= new ZipInputStream(File.OpenRead(filePath));
var filestream=new FileStream(filePath,FileMode.Open,FileAccess.Read);
There is an overload to the ZipFile constructor that takes "any" Stream rather than specifically a FileStream, which you - unsurprisingly - can only create for files.
However, you cannot use the stream returned by GetResponseStream directly, because it's CanSeek property is false. This is because it's a NetworkStream, which can only be read once from beginning to end. SharpZipLib needs random access to read the file contents.
Depending on the size of the ZIP file, loading it in memory may be an option. If you expect large files, writing it to a temporary file may be better.
This should do the trick, without using both ZipInputStream and ZipFile, by enumerating through ZipFile instead:
string url = "https://test/code/304fd9c6-7e53-42a2-845a-624608bfd2ce.zip";
WebRequest webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
WebResponse webResponse = webRequest.GetResponse();
using (var responseStream = webResponse.GetResponseStream())
using (var ms = new MemoryStream())
{
// Copy entire file into memory. Use a file if you expect a lot of data
responseStream.CopyTo(ms);
var zipFile = new ZipFile(ms);
foreach (ZipEntry item in zipFile)
{
Console.WriteLine(item.Name);
using (var s = new StreamReader(zipFile.GetInputStream(item)))
{
Console.WriteLine(s.ReadToEnd());
}
}
}
Console.Read();
PS: starting .NET 4.5, there is support for ZIP files built in. See the ZipArchive class.

Exception, named pipe + serialization

In the below example, NamedPipeServer is started or registered with name “File Transfer”.
The NamedPipeServer reads the content of a source file and creates an instance for “TransferFile” class setting the attributes such as source file name and file content (stream).
Server then serializes the "TransferFile" object and writes to the stream.
NamedPipeClient connects to the NamedPipeServer based whose server name is “File Transfer”.
and reads the stream. After reading the stream, Client deserializes to get the “TransferFile” object.
from the “FileTransfer” object, client creates the target file in specific directory with name from “FileName” attribute and content(byte[]) from “FileContent”.
Exception, when i use formatter.Deserialize(pipeClient).
TransferFile.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileTransfer
{
//file transfer class (serializable)
[Serializable]
public class TransferFile
{
public string FileName;
public Stream FileContent;
}
}
Named Pipe Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Runtime.Serialization;
using FileTransfer;
namespace ServerNamedPipe
{
class Program
{
static void Main()
{
//creating object for file transfer
using (NamedPipeServerStream pipeServer =
new NamedPipeServerStream("File Transfer", PipeDirection.Out))
{
Console.WriteLine("File Transfer Named Pipe Stream is ready...");
Console.Write("Waiting for client connection...");//waiting for any client connections
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
try
{
string strFile = #"c:\Test\1\Srinivas.txt";
//creating FileTransfer Object ans setting the file name
TransferFile objTransferFile = new TransferFile() { FileName = new FileInfo(strFile).Name };
objTransferFile.FileContent = new MemoryStream();
//opening the source file to read bytes
using (FileStream fs = File.Open(strFile, FileMode.Open, FileAccess.Read))
{
byte[] byteBuffer = new byte[1024];
int numBytes = fs.Read(byteBuffer, 0, 1024);
//writing the bytes to file transfer content stream
objTransferFile.FileContent.Write(byteBuffer, 0, 1024);
//below code is to write the bytes directly to the pipe stream
//pipeServer.Write(byteBuffer, 0, 1024);
//Reading each Kbyte and writing to the file content
while (numBytes > 0)
{
numBytes = fs.Read(byteBuffer, 0, numBytes);
objTransferFile.FileContent.Write(byteBuffer, 0, 1024);
//below code is to write the bytes to pipe stream directly
//pipeServer.Write(byteBuffer, 0, numBytes);
}
//setting the file content (stream) position to begining
objTransferFile.FileContent.Seek(0, SeekOrigin.Begin);
//serializing the file transfer object to a stream
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
try
{
//serialzing and writing to pipe stream
formatter.Serialize(pipeServer, objTransferFile);
}
catch (Exception exp)
{
throw exp;
}
}
}
// Catch the IOException that is raised if the pipe is
// broken or disconnected.
catch (IOException e)
{
Console.WriteLine("ERROR: {0}", e.Message);
}
}
}
}
}
Named Pipe Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Runtime.Serialization;
namespace ClientNamedPipe
{
class Program
{
static void Main(string[] args)
{
//connecting to the known pipe stream server which runs in localhost
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", "File Transfer", PipeDirection.In))
{
// Connect to the pipe or wait until the pipe is available.
Console.Write("Attempting to connect to File Transfer pipe...");
//time out can also be specified
pipeClient.Connect();
Console.WriteLine("Connected to File Transfer pipe.");
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
//deserializing the pipe stream recieved from server
FileTransfer.TransferFile objTransferFile = (FileTransfer.TransferFile)formatter.Deserialize(pipeClient);
//creating the target file with name same as specified in source which comes using
//file transfer object
byte[] byteBuffer = new byte[1024];
using (FileStream fs = new FileStream(#"c:\Test\2\" + objTransferFile.FileName, FileMode.Create, FileAccess.Write))
{
//writing each Kbyte to the target file
int numBytes = objTransferFile.FileContent.Read(byteBuffer, 0, 1024);
fs.Write(byteBuffer, 0, 1024);
while (numBytes > 0)
{
numBytes = objTransferFile.FileContent.Read(byteBuffer, 0, numBytes);
fs.Write(byteBuffer, 0, numBytes);
}
}
Console.WriteLine("File, Received from server: {0}", objTransferFile.FileName);
}
Console.Write("Press Enter to continue...");
Console.ReadLine();
}
}
}
You don't say what exception you got, specifically. But just looking at the code, the most obvious problem is that you have a Stream field in your TransferFile object. You can't serialize a Stream object.
One option would be to use a byte[] object instead in the TransferFile class. You can initialize it from your file using File.ReadAllBytes().
Note that serializing the whole file is not very efficient. If you want to make the best use of your pipe bandwidth, you should skip the whole serialization-based scheme, and instead use BinaryWriter.Write(string) to send the file name, and then just write the actual contents of the file to the stream.
For example:
Server:
static void Main()
{
//creating object for file transfer
using (NamedPipeServerStream pipeServer =
new NamedPipeServerStream("File Transfer", PipeDirection.Out))
{
Console.WriteLine("File Transfer Named Pipe Stream is ready...");
Console.Write("Waiting for client connection...");//waiting for any client connections
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
try
{
string strFile = #"c:\Test\1\Srinivas.txt";
using (BinaryWriter writer = new BinaryWriter(pipeServer, Encoding.UTF8, true))
{
writer.Write(strFile);
}
//opening the source file to read bytes
using (FileStream fs = File.Open(strFile, FileMode.Open, FileAccess.Read))
{
fs.CopyTo(pipeServer);
}
}
// Catch the IOException that is raised if the pipe is
// broken or disconnected.
catch (IOException e)
{
Console.WriteLine("ERROR: {0}", e.Message);
}
}
}
Client:
static void Main(string[] args)
{
//connecting to the known pipe stream server which runs in localhost
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", "File Transfer", PipeDirection.In))
{
// Connect to the pipe or wait until the pipe is available.
Console.Write("Attempting to connect to File Transfer pipe...");
//time out can also be specified
pipeClient.Connect();
Console.WriteLine("Connected to File Transfer pipe.");
using (BinaryReader reader = new BinaryReader(pipeClient, Encoding.UTF8, true))
{
string fileName = reader.ReadString();
}
//creating the target file with name same as specified in source which comes using
//file transfer object
using (FileStream fs = new FileStream(#"c:\Test\2\" + fileName, FileMode.Create, FileAccess.Write))
{
pipeClient.CopyTo(fs);
}
Console.WriteLine("File, Received from server: {0}", fileName);
}
Console.Write("Press Enter to continue...");
Console.ReadLine();
}

Categories