FtpWebRequest Upload question
-
Im using the FtpWebRequest object to upload a file to an FTP server. The problem is that if a directory that is part of the remote path does not exist, it fails. Otherwise the file is upload with out error with the code below. I'd almost like to assume that since the request method is UploadFile, that it would create directories as needed. But I must be wrong. So is there be a way to accommodate dynamic creation of the directories? The Error Message [System.Net.WebException] = {"The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."} Here's some code to review if you wish. The UriBuilder
UriBuilder uB = new UriBuilder();
uB.Scheme = Uri.UriSchemeFtp;
uB.Host = ConfigurationManager.AppSettings["FTPRemoteHost"].ToString();
uB.UserName = ConfigurationManager.AppSettings["FTPRemoteUser"].ToString();
uB.Password = ConfigurationManager.AppSettings["FTPRemotePass"].ToString();
FileInfo uFInfo = new FileInfo(localpdf);
uB.Path = remotepath + uFInfo.Name;The value of the UriBuider Uri property
{ftp://username:password@myftpserver/existingDirectory/missingDirectory/mydocument.pdf}
The function I'm working with
public bool UploadFile(Uri serverUri, string localFile) { if (serverUri.Scheme != Uri.UriSchemeFtp) return false; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; if (File.Exists(localFile) == false) return false; StreamReader sourceStream = new StreamReader(localFile); byte\[\] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); if (fileContents.Length <= 0) return false; request.ContentLength = fileContents.Length; try { Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); return false; } FtpWebResponse response = (FtpWebResponse)request.GetResponse();
#if(DEBUG)
WriteEvent(response.StatusDescription, EventLogEntryType.Information);
#endif