2013-03-15 2 views
1

나는 이것에 대해 1 월에 포스트를 만들었지 만 결코 해결되지 않았습니다. 저는 Youtube Teams 웹 사이트에 ftp 프로그램을 사용하고 있습니다. 이상한 이유로, HTML 코드가 생성되고 성공적으로 전송되지만 이미지가 손상됩니다. 바이너리 모드가 true로 설정되고 사용 권한이 모두 올바른지 확인했습니다. 아무것도 작동하는 것 같습니다.FTP에서 이미지 손상, 이진 모드 켜기

누군가 나를 도울 수 있습니까? 당신이에 Encoding.UTF8.GetBytes()를 사용하는 것 같습니다,

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 ... 

    } 

} 
+0

에 대한 몇 가지 다른 이름 지정 규칙을 고려하시기 바랍니다'안티 패턴 .. – Blindy

답변

1

확인이 코드는 읽기 어려운,하지만 :

이 내 질문에 관련 코드의 우리의 일부입니다 image (sourceStreamTwo) Byte [] fileContentTwo를 선언 할 때.

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

변경하는 것이이는 지금보고되지 않은 가정합니다

Byte[] fileContentTwo; 

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

에 :

편집는 - 대신하여 FileStream을 사용 - 당신이 위해 StreamReader를 필요로하지 않는, 얘기를 깜빡 했네요 전체 스트림을 사용할 수없는 네트워크의 경우 Creating a byte array from a stream

.net 4 이상 Stream.CopyTo()을 사용하면 스트림의 중단을 처리 할 때 더 안전합니다. 자세한 내용은 위의 질문과 답변을 참조하십시오.

그리고 너는 잘해야한다. 인코딩은 텍스트를 의미하고 이미지는 바이너리를 의미합니다.

또한 당신이`에서는 try..catch (예) {던져 전}의 적은 설 수 귀하의 변수 :

+0

가 좋아, 내가 ' 지금이 일을하려고하는 m,하지만 '최고의 일치 "system.io.binaryreader.binaryreader (system.io.stream"사용에 대한 일부 잘못된 arguements 있습니다. 오류가 주어진 해요.뿐만 아니라 streamreader 포함하지 길이에 대한 정의 – sysmic

+0

@ user1942062 나는 내 iPad에 글을 쓰고 있었고 모든 코드를 확인하지 못했습니다. 그냥 지금 확인하고 다시 약간의 세부 사항을 추가했습니다 .. –

+0

도움을 주셔서 감사합니다! 그냥 두 개의 파일을 추가해야했습니다 (파일을 저장하는 디렉토리를 잘못 작성했기 때문에 그냥 슬래시를 사용합니다). ell) – sysmic