将图像上载到桌面中的文件夹

时间:2016-12-15 07:40:51

标签: c# asp.net file-upload upload directory

我无法将图片上传到指定的文件夹。这是代码。

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

当我点击上传时,标签会在代码中写入Uploaded Successfully!!,但图片不在代码中的指定文件夹中。请帮忙谢谢!

3 个答案:

答案 0 :(得分:1)

尝试将代码更改为

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

我在PICTURES之后添加了一个反斜杠,以便构建正确的文件名。

答案 1 :(得分:1)

在图片之后放置一个\

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

答案 2 :(得分:1)

问题在于这一行:

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

添加斜杠会修复它:

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

更加平台无关的解决方法是:

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

最好的方法是:

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