Thursday, 22 August 2013

ASP.NET/C# FTP Upload

ASP.NET/C# FTP Upload

I have spent the better part of a day researching this issue (including
numerous Stack Overflow questions, but none have helped.
I have a simple FTP upload utility on an ASP.NET page. Here is the code
behind:
protected void btnUpload_Click(object sender, EventArgs e)
{
BLLSites site = (BLLSites)Session["SelectedSite"];
List<string> allowableExtensions = GetAllowableFileExtensions();
string extension = System.IO.Path.GetExtension(FileUpload.FileName);
bool extensionAllowed = allowableExtensions.Any(x =>
String.Equals(x, extension,
StringComparison.InvariantCultureIgnoreCase));
string folderPath = "ftp://MyPath/MyFolder";
string uploadPath = "ftp://MyPath/MyFolder/MyFile.pdf";
if (extensionAllowed)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new
Uri(uploadPath));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.UseBinary = true;
request.Credentials = new NetworkCredential("UserName",
"Password", "localhost");
request.ContentLength = FileUpload.FileContent.Length;
request.KeepAlive = false;
// Copy the contents of the file to the request stream.
string fullPath = Path.GetFileName(FileUpload.FileName);
//BinaryReader reader = new BinaryReader(FileUpload.FileContent);
byte[] fileContents = new
BinaryReader(FileUpload.FileContent).ReadBytes((int)FileUpload.FileContent.Length);
try
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0,
fileContents.Length);
requestStream.Close();
}
}
catch (Exception ex)
{
...
}
I am developing in Visual Studio 2010 using .NET 4.0. I am uploading to an
Amazon Cloud server that has an FTP site running in IIS. When I run my
application in debug mode and execute the upload function, the file
appears on the Amazon server. The problem occurs when I deploy the code to
the web server (also on the Amazon server). I get the following exception
whether I launch the site directly on the server or through my own web
browser:
The remote server returned an error: (501) Syntax error in parameters or
arguments
The exception occurs during the section of code:
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
}
I have checked all of my permissions on the FTP site, but everything seems
OK. I have tried both PASSIVE and ACTIVE mode. Nothing seems to work. Any
help would be greatly appreciated.

No comments:

Post a Comment