Ben
Ben

Reputation: 5777

FTP not uploading file correctly

I'm trying to make a small personal screen capture app where I can press a shortcut key and it uploads a full screenshot of the screen.

I have managed to get the file to upload to my website but the problem I'm having is, when you go to the URL, it appears as a broken image.

Here's my code:

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");
    }
}

Here is an example: Screenshot

Any ideas?

Upvotes: 3

Views: 1745

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

This is the problem:

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

You're reading your file as if it were UTF-8-encoded text. It's not - it's an image. Arbitrary binary data.

Use:

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

and everything should be okay.

The rest of your code could still do with some TLC - fixing naming conventions, using using statements appropriately etc - but treating arbitrary binary data as text is the main problem here.

Upvotes: 3

Related Questions