-4

I have this string variable for example:

ftp://ftp.newsxpressmedia.com/Images/CB 967x330.jpg

And I need it to be

ftp://ftp.newsxpressmedia.com//Images//CB 967x330.jpg

I need to add / after each directory. In this specific example there are two directories but in other files it might be one or more directories that I need to add /

This is the code and what i tried:

public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
        {                       
            try
            {
                BackgroundWorker bw = sender as BackgroundWorker;
                string filenameonly = Path.GetFileName(file);
                string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
                string fileurl = "ftp://" + file;
                FtpWebRequest reqFTP;                
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);                                
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse resp = (FtpWebResponse)reqFTP.GetResponse();
                Int64 FileContLen = resp.ContentLength;

fileurl contain for example ftp://ftp.test.com/myimage.jpg

The problem in this format i'm getting exception on FtpWebResponse resp = (FtpWebResponse)reqFTP.GetResponse(); that the file is not exist access denied.....etc

If i'm not wrong the reason it's not finiding the file is that the format of fileurl is wrong. So i need format the fileurl.

FileContLen should get the file size from my ftp server. I have in form1 the files names and links from my ftp already and i'm looping on the List and send to this method each time a file. But it's never getting to the FileContLen and my guess is that the fileurl is not the correct path as it should be. It is the correct path but should be with // after a directory and not /

This is the excpetion im getting on the line: FtpWebResponse resp = (FtpWebResponse)reqFTP.GetResponse();

The remote server returned an error: (550) File unavailable (e.g., file not found, no acces

System.Net.WebException was caught
  HResult=-2146233079
  Message=The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
  Source=System
  StackTrace:
       at System.Net.FtpWebRequest.CheckError()
       at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
       at System.IO.Stream.Close()
       at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
       at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)
       at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
       at System.Net.FtpWebRequest.GetResponse()
       at FTP_ProgressBar.FtpProgress.DownloadFtpContent(Object sender, String file, String filesdirectories, String fn) in c:\ftp_progressbar\FTP_ProgressBar\FtpProgress.cs:line 266
  InnerException: 

If i'm downloading a file same way but only downloading with getting the file size it's working fine. This is how i'm downloading a file:

public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
        {                       
            try
            {
                BackgroundWorker bw = sender as BackgroundWorker;
                string filenameonly = Path.GetFileName(file);
                string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
                string fileurl = "ftp://" + file;
                FtpWebRequest reqFTP;                
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);                                
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;

                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
                //reqFTP.UseBinary = true;
                reqFTP.Proxy = null;                 
                //reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (!Directory.Exists(ftpdirectories))
                {
                    Directory.CreateDirectory(ftpdirectories);
                }
                FileStream writeStream = new FileStream(ftpdirectories + "\\" + filenameonly, FileMode.Create);
                string fnn = ftpdirectories + "\\" + filenameonly;
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                //FileSize = responseStream.Length;//new FileInfo(fnn).Length;//f.SourceFile).Length;
                // to correct long FileSize the fn is not the full file location need path too !?
                //string FileSizeDescription = GetFileSize(FileSize);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                    //FileSize = responseStream.Length;
                    //string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(bytesRead), FileSizeDescription);
                    //bw.ReportProgress((int)(((decimal)bytesRead / (decimal)FileSize) * 100), SummaryText);
                }        
                writeStream.Close();
                response.Close(); 
            }
            catch (WebException wEx)
            {
                //MessageBox.Show(wEx.Message, "Download Error");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Download Error");
            }
        }
    }

Downloading only a file is working fine the problem is that i want to get the file size on the ftp server and then calculate and report to the bw(backgroundworker) progressreport the file size and speed. And i can't fine how to do it i'm not getting the file size so i tried the code in my top of my question.

  • And that url doesn't seem right to me. Why do you need it? – L.B Dec 07 '14 at 21:50
  • BTW: `file is not exist` and `access denied` are completely different things. What error do you get with the code in question? – L.B Dec 07 '14 at 21:52
  • L.B since i;m getting the exception on the line explained in my question. – Horhe El Fenenado Dec 07 '14 at 21:52
  • What exception are you getting? Please paste the exception in your question. – Rufus L Dec 07 '14 at 21:53
  • And you think replacing `/`s with `//`s would solve your problem? – L.B Dec 07 '14 at 21:53
  • It's *highly unlikely* that you need to change `/` to `//`. That would be a totally non-standard thing to do. If you can download the file when the url contains single slashes, it makes no sense at all that you would need to double the slashes in order to get the file size. See http://stackoverflow.com/questions/16197338/c-sharp-ftp-size-command-doesnt-work-on-all-ftp-servers, which might be useful to you. – Jim Mischel Dec 07 '14 at 22:14

1 Answers1

1

Adding addition / characters is reasonably easy if you are certain the URLs are consistent - you can use a mixture of a Uri object to conveniently section the URL for you, combined with the string Replace() method:

class Program
{
    static void Main(string[] args)
    {

        var myUri = new Uri("ftp://ftp.newsxpressmedia.com/Images/CB 967x330.jpg");

        var modifiedUri = new Uri(string.Format( "{0}//{1}"  
                                                , myUri.Scheme  
                                                , (myUri.Host + myUri.LocalPath).Replace("/", "//")
                                                ));

        Console.ReadKey();
    }
}

However.... I doubt this is the source of your particular problem because you shouldn't need to double up the forward slashes like that. Are you using the correct protocol? Can you confirm the URL you are using?

slugster
  • 49,403
  • 14
  • 95
  • 145
  • 1
    As in your last paragraph, you know it is not an answer. so what does this answer? just a big comment? – L.B Dec 07 '14 at 22:02
  • @L.B Just answering one part of his question. He asked how to add more slashes, I gave him an example. What he does with it is.... his problem. – slugster Dec 07 '14 at 22:04
  • slugster yes confirmed i added to my question at bottom the code how i'm using the method only to download files and it is working fine i checked all files saved on hard disk fine with directories. The problem is i want to report to the backgroundworker oone thing. In real time how much left to download one size how much downloaded so far and right to it out of for example: 12kb/123kb maybe in the future to report the speed of the file the speed fo the download in real time. – Horhe El Fenenado Dec 07 '14 at 22:04
  • slugster you right but i'm not sure if this is the problem so i changed my question content since i thought it's the problem but not sure. It was my mistake so i edited my question trying to explain what i'm trying to do. – Horhe El Fenenado Dec 07 '14 at 22:05
  • @HorheElFenenado As the nature of your question has changed I would suggest you delete this one and write a new question - rather than morphing the current question into something different. – slugster Dec 07 '14 at 22:06