1

I made a post back in january about this, but it was never solved. I have been working on a program to ftp to my Youtube Teams website. For some odd reason, the HTML code generated works and is transferred successfully, but the images come through corrupted. I've made sure that Binary mode is set to true and permissions are all correct. Nothing seems to work.

Can somebody help me?

This is our part of the Code which is relevant to my question:

namespace TMNGP_FTP
{
    partial class Form1
    {
        // some functions and properties for the form
        UriBuilder ftpurl;
        String ftpurlstr = "ftp://tmngp.heliohost.org";
        static String ftpusername = "*******";
        static String ftppassword = "*******";

        public static string GenerateFileName(string context)
        {
            return context + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
        }

        public void openpic_Click(object sender, System.EventArgs e)
        {
            //Wrap the creation of the OpenFileDialog instance in a using statement,
            //Rather than manually calling the dispose method to ensure proper disposal
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = "Open Image";
                dlg.Filter = "png files (*.png)|*.png";

                if (dlg.ShowDialog() == DialogResult.OK)
                {

                    string folderName = @"c:\TMNGP_Web_Files";

                    string pathString = folderName + @"\htTemp";
                    pathString = pathString + @"\imgs";

                    if (!System.IO.Directory.Exists(pathString))
                    {
                        System.IO.Directory.CreateDirectory(pathString);
                    }

                    string destFileName = pathString + @"\" + dlg.SafeFileName.ToString();

                    System.IO.File.Copy(dlg.FileName, destFileName, true);
                    DisplImg.Image = new Bitmap(dlg.OpenFile());
                    DisplImg.ImageLocation = destFileName;
                }
            }

        }

        private FtpClient ftpnew = null;

        public void textgen_Click(object sender, System.EventArgs e)
        {

            string folderName = @"c:\TMNGP_Web_Files";

            string pathString = folderName + @"\htTemp";

            if (!System.IO.Directory.Exists(pathString))
            {
                System.IO.Directory.CreateDirectory(pathString);
            }

            string fileName = GenerateFileName("HT");

            pathString = pathString + @"\" + fileName;

            Console.WriteLine("Path to my file: {0}\n", pathString);

            if (!System.IO.File.Exists(pathString))
            {
                //System.IO.FileStream fs = System.IO.File.Create(pathString);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
                {
                    file.WriteLine("<div class='simple_overlay' id='news_archive/" + DisplImg.ImageLocation.Substring(31) + "' style='display:none;'>");
                    file.WriteLine("<a class='close'></a>");
                    file.WriteLine("<img src='news_archive/" + DisplImg.ImageLocation.Substring(31) + "'/>");
                    file.WriteLine("<div class='details'>");
                    file.WriteLine("<h3> " + txtTitle.Text + " </h3>");
                    file.WriteLine("<h4> " + TxtInfo.Text + " </h4>");
                    file.WriteLine("<p>" + Desctext.Text + "</p>");
                    file.WriteLine("</div>");
                    file.WriteLine("</div>");
                }

                if(radioButton1.Checked)
                {
                    ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "NGP/news_archive/");
                    ftpurlstr = "/public_html/NGP/news_archive";
                }
                else
                {
                    ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "TM/news_archive/");
                    ftpurlstr = "/public_html/TM/news_archive";
                }

                try
                {
                    //string filenametwo = System.IO.Path.GetFullPath(@"c:\TMNGP_Web_Files\htTemp\"+fileName);
                    string filenamethree = System.IO.Path.GetFullPath(DisplImg.ImageLocation.ToString());
                    Console.WriteLine("{0}", filenamethree);
                    Console.WriteLine(pathString);
                    //string ftpfullpath = ftpurl;
                    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create((@"ftp://tmngp.heliohost.org" + ftpurlstr + fileName).ToString());
                    Console.WriteLine("{0}", ftpurl + fileName);
                    ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
                    ftp.KeepAlive = true;
                    ftp.UseBinary = true;
                    ftp.Method = WebRequestMethods.Ftp.UploadFile;
                    StreamReader sourceStreamone = new StreamReader(@"c:\TMNGP_Web_Files\htTemp\" + fileName);
                    byte[] fileContentsone = Encoding.UTF8.GetBytes(sourceStreamone.ReadToEnd());
                    sourceStreamone.Close();
                    ftp.ContentLength = fileContentsone.Length;
                    Stream requestStreamone = ftp.GetRequestStream();
                    requestStreamone.Write(fileContentsone, 0, fileContentsone.Length);
                    requestStreamone.Close();
                    FtpWebResponse ftpresponseone = (FtpWebResponse)ftp.GetResponse();
                    Console.WriteLine("Upload File Complete, status {0}", ftpresponseone.StatusDescription);
                    ftpresponseone.Close();

                }
                catch (WebException ex)
                {
                    throw ex;
                }
                try
                {
                    string imgfile = DisplImg.ImageLocation.Substring(31);
                    FtpWebRequest ftp2 = (FtpWebRequest)FtpWebRequest.Create((@"ftp://tmngp.heliohost.org" + ftpurlstr + imgfile).ToString());
                    ftp2.Credentials = new NetworkCredential(ftpusername, ftppassword);
                    ftp2.KeepAlive = true;
                    ftp2.UseBinary = true;
                    ftp2.Method = WebRequestMethods.Ftp.UploadFile;
                    StreamReader sourceStreamtwo = new StreamReader(DisplImg.ImageLocation.ToString());
                    byte[] fileContentstwo = Encoding.UTF8.GetBytes(sourceStreamtwo.ReadToEnd());
                    sourceStreamtwo.Close();
                    ftp2.ContentLength = fileContentstwo.Length;
                    Stream requestStreamtwo = ftp2.GetRequestStream();
                    requestStreamtwo.Write(fileContentstwo, 0, fileContentstwo.Length);
                    requestStreamtwo.Close();
                    FtpWebResponse ftpresponsetwo = (FtpWebResponse)ftp2.GetResponse();
                    Console.WriteLine("Upload File Complete, status {0}", ftpresponsetwo.StatusDescription);
                    ftpresponsetwo.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                MessageBox.Show("FTP Complete");
            }
            else
            {
                Console.WriteLine("File \"{0}\" already exists.", fileName);
                return;
            }
        }



        // a bunch of Windows Form Designer generated code ...

    }

}
Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32
sysmic
  • 23
  • 5

1 Answers1

1

Ok this code is hard to read, BUT, it looks like you are using Encoding.UTF8.GetBytes() on the image (sourceStreamTwo) when you declare Byte[] fileContentTwo.

Edit - forgot to mention, you don't need the StreamReader - use a FileStream instead:

FileStream sourceStreamtwo = new FileStream(DisplImg.ImageLocation.ToString(), FileMode.Open);

Change that to

Byte[] fileContentTwo;

using (BinaryReader br = new BinaryReader(sourceStreamtwo))
{
    fileContentsTwo = br.ReadBytes((int)sourceStreamtwo.Length);
    // rest of code that deals with sourceStreamTwo
}

Note this assumes you aren't reading from a network where you might not have the whole stream available, see Creating a byte array from a stream

In .net 4 or higher you can use Stream.CopyTo() which is safer as it handles interruptions in the stream - again see above question and answers for more info.

And you should be good. Encoding is meant for text, images are binary.

Also please consider some different naming conventions for your variables :)

Community
  • 1
  • 1
Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32
  • Ok, I'm trying to do this now, but I'm being given an error that 'The best match for "system.io.binaryreader.binaryreader(system.io.stream" has some invalid arguements' for the using. Aswell as streamreader not containing a definition for length. – sysmic Mar 15 '13 at 04:34
  • @user1942062 I was writing on my iPad and didn't check all the code. Just checked it now and added some details again. – Dmitriy Khaykin Mar 15 '13 at 04:43
  • Thank you for your help! I was able to make it work because of you! I just needed to add two more things to it (just slashes because I miswrote the directories to place the files aswell) – sysmic Mar 15 '13 at 05:19
  • @user1942062 Awesome! Glad to help - don't forget you can accept the answer if it was helpful here on StackOverflow :) – Dmitriy Khaykin Mar 15 '13 at 05:21