【问题标题】:FTP not uploading file correctlyFTP没有正确上传文件
【发布时间】:2012-10-24 06:08:08
【问题描述】:

我正在尝试制作一个小型个人屏幕截图应用程序,我可以在其中按下快捷键并上传屏幕的完整屏幕截图。

我已设法将文件上传到我的网站,但我遇到的问题是,当您转到 URL 时,它显示为损坏的图像。

这是我的代码:

private void CaptureFullScreen()
{
    string file = DateTime.Now.ToString("ddmmyyyyhhmmss") + ".jpg";
    string file_store = screenshotDir + "\\" + file;

    Rectangle bounds = Screen.GetBounds(Point.Empty);
    using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
    {
        using(Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
        }

        bitmap.Save(file_store, ImageFormat.Jpeg); 
    }

    //System.Diagnostics.Process.Start(file);
    ShowBalloonTip("Uploading...", "Screen Capture is being uploaded", ToolTipIcon.Info, 1000);
    FtpFileUpload(file_store, file);
}
private void FtpFileUpload(string file_store, string file_name)
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://passion4web.co.uk/www/apps/imgcap/" + file_name);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential("username", "password");

        StreamReader strRead = new StreamReader(file_store);
        byte[] fileContents = Encoding.UTF8.GetBytes(strRead.ReadToEnd());
        strRead.Close();
        request.ContentLength = fileContents.Length;

        Stream reqStream = request.GetRequestStream();
        reqStream.Write(fileContents, 0, fileContents.Length);
        reqStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        string url = "http://passion4web.co.uk/apps/imgcap/" + file_name;
        string resp = response.StatusDescription;

        ShowBalloonTip("Screenshot uploaded", "Click this balloon to open", ToolTipIcon.Info, 5000, url);

        response.Close();
    }
    catch (Exception ex)
    {
        //Ignore this - used for debugging
        MessageBox.Show(ex.ToString(),"Upload error");
        MessageBox.Show(file_name + Environment.NewLine + file_store, "Filename, Filestore");
    }
}

这是一个例子: Screenshot

有什么想法吗?

【问题讨论】:

    标签: c# upload ftp


    【解决方案1】:

    这就是问题所在:

    StreamReader strRead = new StreamReader(file_store);
    byte[] fileContents = Encoding.UTF8.GetBytes(strRead.ReadToEnd());
    

    您正在阅读您的文件,就好像它是 UTF-8 编码的文本一样。它不是——它是一个图像。任意二进制数据。

    用途:

    byte[] fileContents = File.ReadAllBytes(file_store);
    

    一切都会好起来的。

    您的其余代码仍然可以使用一些 TLC - 修复命名约定,适当地使用 using 语句等 - 但将任意二进制数据视为文本是这里的主要问题。

    【讨论】:

      猜你喜欢
      • 2013-12-18
      • 1970-01-01
      • 2011-11-06
      • 2015-04-22
      • 1970-01-01
      • 2017-02-25
      • 2014-04-07
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多