C# upload XLS file into FTP - c#

I use following code to upload *.xls file into FTP. It works fine for uploading, but the content of *.xls file in FTP all mess up
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(#"ftp://www.xxxxxx.com" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
StreamReader sourceStream = new StreamReader(filePath);
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);
response.Close();
Any one know how to fix this problem???????

Insted of this:
StreamReader sourceStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
Try to use this:
byte[] fileContents = File.ReadAllBytes(filePath);
It might be encoding\decoding problem.

Related

Decoding and encoding PDF to send through FTP

Hello there fellow programmers!
I have an issue with sending PDF through FTP. I want to copy propely created PDF to FTP directory, unfortunately file i send through has proper size but i cannot open it with any PDF editor. I've tried searching soulutions but my converting and encoding does not seem to work. Here is my code:
public string SendPDF(string FileNamePath, string ShortFileName)
{
string Response = string.Empty;
//FullPath is generated in class constructor
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FullPath+#"\"+ShortFileName+".pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Password);
//FileNamePath is directory of source file
byte[] fileContents= File.ReadAllBytes(#FileNamePath + ".pdf");
string pdfBase64 = Convert.ToBase64String(fileContents);
using(var stream = GenerateStreamFromString(pdfBase64))
{
request.ContentLength = stream.Length;
using (Stream requestStream = request.GetRequestStream())
{
stream.CopyTo(requestStream);
requestStream.Close();
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Response = "Upload File PDF Complete, status" + Convert.ToString(response.StatusDescription);
}
return Response;
}
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Also, I've tried code below but it has the same issue:
byte[] fileContents ;
using (StreamReader sourceStream = new StreamReader(FileNamePath + ".pdf"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
Sending through XML file works completely fine. Thank you in advance and please don't be harsh this is my first question here :3
I found the solution. The issue was lack of parameter request.UseBinary = true. Here is proper code:
public string SendPDF(string FileNamePath, string ShortFileName)
{
string Response = string.Empty;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPPath+#"\"+ShortFileName+".pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.Credentials = new NetworkCredential(User, Password);
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(FileNamePath + ".pdf"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Response = "Upload File PDF Complete, status" + Convert.ToString(response.StatusDescription);
}
return Response;
}

How to preserve utt-8 signature with requeststream.write

I'm using the following code to send an XML file by FTP:
var request = (FtpWebRequest) WebRequest.Create(destination);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(UserName, Password);
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(originpath + filename))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
This seems to work, except the format of the file at the origin is utf-8 with signature, and it's without signature at the destination.
I've tried to preserve the utf encoding, but I seem to have lost the BOM.
Is this a problem with my code - specifically, with the way that requeststream.write works?

Upload Multiple Ftp Files once

Im working at C#, I have 4 files, How to upload them all at once?
I have this, But this only works at 1 file.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("(secret)/keystock1.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("keystock1.txt");
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("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
You can achieve this using Async tasks. A class like following would achieve this:
public class FileUploadsManager
{
//pass in the list of file paths which u want to upload.
public static async void UploadFilesAsync(string[] filePaths)
{
List<Task> fileUploadingTasks = new List<Task>();
foreach (var filePath in filePaths)
{
fileUploadingTasks.Add(UploadFileAsync(filePath));
}
await Task.WhenAll(fileUploadingTasks);
}
public static Task UploadFileAsync(string filePath)
{
return Task.Run(async () =>
{
//this is your code with a few changes
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(
string.Format("(secret)/{0}", Path.GetFileName(filePath))
);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(await sourceStream.ReadToEndAsync());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = await request.GetRequestStreamAsync();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
Console.WriteLine("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
});
}
}
You can call this as follows:
string[] paths = new string[] { "C:\file1.txt", "C:\file2.txt", "C:\file2.txt" };
FileUploadsManager.UploadFilesAsync(paths);

How to send an excel file to FTP using C#?

I using the following code to send an excel file to FTP. File is sending, File size is also same. But file contains only spaces.
ftpAddress = "X.X.X.X";
outFilePath = "MyFolder/Sample.xls";
inFilePath = "D:/Hello.xls";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpAddress + "/" + outFilePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(userId, password);
//FileStream stream = File.OpenRead(inFilePath);
byte[] fileContents = File.ReadAllBytes(inFilePath);
//byte[] buffer = new byte[stream.Length];
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
//Shows confirm message
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine(response);
response.Close();
Please help. Thanks in advance.
Source: http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
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.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
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);
response.Close();
}
}
}
}

Uploading a WebImage to FTP

I am using ASP.Net MVC 4 and WebImage helpers. I need to upload my WebImage object via FTP. I just don't know how to get the WebImage parameters to send to my RequestStream.Write
Here is some code...
WebImage photo = WebImage.GetImageFromRequest();
string fileName = System.IO.Path.GetFileName(photo.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPaddress +"/images/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("****", "*****");
request.UsePassive = true;
request.ContentLength = ???????;
byte[] buffer = ????????; //It's not photo.GetBytes;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, request.ContentLength);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
And will I be able to use the photo.Save() to the FTP path afterwards?
byte [] fileContents = photo.GetBytes();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
That's how you do it, silly me.

Categories