Chloven Tan
Chloven Tan

Reputation: 65

Uploading an image to a folder in desktop

I can't get to upload an image to a specified folder. Here's the code.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (FileUploader.HasFile)
    {
        try
        {
             string filename = Path.GetFileName(FileUploader.FileName);
             FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES" + filename);
             Label1.Text = "Uploaded Successfully!!";
        }
        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

When I click on upload, the label does says Uploaded Successfully!! as written in the code but the picture is not in the specified folder in the code. Please help thank you!

Upvotes: 0

Views: 95

Answers (3)

Abhinaw Kaushik
Abhinaw Kaushik

Reputation: 627

Put a \ after the PICTURES:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (FileUploader.HasFile)
    {
        try
        {
             string filename = Path.GetFileName(FileUploader.FileName);
             FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);
             Label1.Text = "Uploaded Successfully!!";
        }
        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

Upvotes: 1

John Wu
John Wu

Reputation: 52240

Problem is this line:

FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES" + filename);

Adding a slash would fix it:

FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);

A more platform-agnostic way to fix it would be:

const string folder = @"D:\Users\SGG90745\Desktop\PICTURES" 
...
var path = folder + Path.DirectorySeparatorChar + filename;

And the best way to do it is:

const string folder = @"D:\Users\SGG90745\Desktop\PICTURES" 
...
var path = Path.Combine(folder, filename);

Upvotes: 1

Ralf Bönning
Ralf Bönning

Reputation: 15415

Try to change your code to

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (FileUploader.HasFile)
    {
        try
        {
             string filename = Path.GetFileName(FileUploader.FileName);
             FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);
             Label1.Text = "Uploaded Successfully!!";
        }
        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

I have simply added a backslash after PICTURES in order to build the correct file name.

Upvotes: 1

Related Questions