Here's some problem with transporting .csv file to FTP server. Before transfering it's okay, but when i'm checking it on FTP it looks like broken or something:
"ЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ T8пїЅпїЅпїЅпїЅпїЅпїЅ\p3>#L #E8?5=:> BпїЅaпїЅ="
Is it problem with encoding? I'm using this method of download:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxxxxxxx.xx/" + name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential("xxxx", "qweqwe123");
StreamReader sourceStream = new StreamReader("F:\\" + xxxx);
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();
response.Close();
Don't like to answer under my aquestions, but it's too long for comment:
Solved, maybe somebody have this problem. Try to use this upload method:
FileInfo toUpload = new FileInfo("log.txt");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://csharpcoderr.com/public_html/" + toUpload.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("name", "pass");
Stream ftpStream = request.GetRequestStream();
FileStream fileStream = File.OpenRead("log.txt");
byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
bytesRead = fileStream.Read(buffer, 0, 1024);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
fileStream.Close();
ftpStream.Close();
I can across this question with the same issue.
Expanding on Brawl_Ups solution...
And it seems that its best to use the BinaryReader for binary files.
This is a snippet I eventfully came up with...
This is a current work in progress and any edits are welcome.
public string UploadFile()
{
string sRetVal = string.Empty;
string sFullDestination = this.DestinatinFullIDPath + this.UpLoadFileName;
try
{
if ((this.CreateDestinationDir(this.DestinatinFullModulePath) == true) &
(this.CreateDestinationDir(this.DestinatinFullIDPath) == true))
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(sFullDestination);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(this.UserName, this.Password);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.EnableSsl = false;
byte[] fileContents;
using (BinaryReader binReader = new BinaryReader(File.OpenRead(this.UpLoadFullName)))
{
FileInfo fi = new FileInfo(this.UpLoadFullName);
binReader.BaseStream.Position = 0;
fileContents = binReader.ReadBytes((int)fi.Length);
}
ftpRequest.ContentLength = fileContents.Length;
using (Stream requestStream = ftpRequest.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())
{
sRetVal = string.Format("Upload File Complete, status {0}", response.StatusDescription);
}
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
return sRetVal;
}
Related
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;
}
I need to upload text file from local machine to ftp server using c#.
I've tried folowing code but it did't work.
private bool UploadFile(FileInfo fileInfo)
{
FtpWebRequest request = null;
try
{
string ftpPath = "ftp://www.tt.com/" + fileInfo.Name
request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Credentials = new NetworkCredential("ftptest", "ftptest");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.Timeout = 60000; // 1 minute time out
request.ServicePoint.ConnectionLimit = 15;
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open))
{
int dataLength = (int)fs.Length;
int bytesRead = 0;
int bytesDownloaded = 0;
using (Stream requestStream = request.GetRequestStream())
{
while (bytesRead < dataLength)
{
bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
bytesRead = bytesRead + bytesDownloaded;
requestStream.Write(buffer, 0, bytesDownloaded);
}
requestStream.Close();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
request = null;
}
return false;
}// UploadFile
any suggestions ???
You need to actually send the request by calling GetResponse().
You can also make your code much simpler by calling fs.CopyTo(requestStream).
I tinkered around with a bit ftp code and got the following, which seems to work pretty well for me.
ftpUploadloc is a ftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt
ftpUsername and ftpPassword should be self explanatory.
Finally currentLog is the location of the file you're uploading.
Let me know how this worked out for you, if anyone else has any other suggestions I welcome those.
private void ftplogdump()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(currentLog);
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();
// Remove before publishing
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
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();
}
}
}
}
I'm having some trouble with uploading a file to a FTP server from C#. My code works well on localhost, but on the live environment it keeps giving me a The operation has timed out. exception.
I use the following code:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath + "/orders.csv");
request.UsePassive = true;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = -1;
StreamReader sourceStream = new StreamReader(context.Server.MapPath("~/App_Data/orders.csv"));
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();
Where ftpPath is the URL of my FTP server: ftp://myserver.com
Does anyone know what I'm doing wrong here? :-)
Thanks in advance.
Some time we need to download, upload file from FTP server. Here is some example to FTP operation.
For this we need to include one namespace and it is. using System.Net
public void DownloadFile(string HostURL, string UserName, string Password, string SourceDirectory, string FileName, string LocalDirectory)
{
if (!File.Exists(LocalDirectory + FileName))
{
try
{
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(LocalDirectory + FileName, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
catch (Exception ex)
{
throw ex;
}
}
}
This was a permission issue. Seems like the FTP user on my webhotel was restricted (somehow) Tried with another FTP with a user with full permissions and it worked.
I have some images on server i want to upload it on another server i make code to upload all images on server but it is OK to upload on local but i didn't know what is wrong in that it can't be upload on server
try
{
byte[] content;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(500000);
br.Close();
}
response.Close();
string CompleteDPath = "ftp path";
string UName = "abc";
string PWD = "123";
WebRequest reqObj = WebRequest.Create(CompleteDPath + file_name);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(UName, PWD);
reqObj.GetRequestStream().Write(content, 0, content.Length);
reqObj = null;
//FileStream fs = new FileStream(file_name, FileMode.Create);
//BinaryWriter bw = new BinaryWriter(fs);
//bw.Write(content);
//fs.Close();
//bw.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
have a try;
byte[] content;
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url);
WebResponse response1 = request1.GetResponse();
Stream stream = response1.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes((int)stream.Length);
br.Close();
}
response1.Close();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp_path");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("abc", "123");
request.ContentLength = content.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(content, 0, content.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();