【问题标题】:Store uploaded file to a created directory将上传的文件存储到创建的目录
【发布时间】:2014-08-12 11:11:58
【问题描述】:

我目前正在开发一个用 asp 开发的网站。一页允许用户发送消息和上传文件。该文件已上传,我可以将其保存到目录中没有问题。但是,客户端需要为每个登录用户创建一个目录,然后将上传的文件保存到该特定目录。我已经设法使用以下代码创建了目录。

if (!Directory.Exists("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId()))
        {
            Directory.CreateDirectory("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId());
        }

根据需要创建目录。但是我似乎无法将文件保存到该特定目录。相反,它将文件保存到上传目录。有谁知道我该怎么做。提前致谢

我保存文件的代码

FileUpload1.SaveAs("\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId()));

【问题讨论】:

  • 你的意思是文件保存到父目录“Upload”而不是“\\Upload\\ + username + userguid”?
  • @andrey.shedko 是的,我就是这个意思

标签: c# asp.net


【解决方案1】:

通过引入变量来清理创建目录的代码:

string userDirectory = "\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId();

if (!Directory.Exists(userDirectory))
{
    Directory.CreateDirectory(userDirectory);
}

然后在保存到该目录时,请确保指定 文件名 而不是目录:

string filename = Path.Combine(userDirectory, FileUpload1.Filename);

FileUpload1.SaveAs(filename);

请参阅Don't overwrite file uploaded through FileUpload control 以确保您不会覆盖具有相同名称的文件。

【讨论】:

  • 你是救生员!非常感谢
【解决方案2】:

我认为您在 FileUpload1.SaveAs(...) 方法中缺少文件名。根据MSDN,需要找回FileUpload1.FileName

【讨论】:

    【解决方案3】:

    您的解决方案:

    string targetPath = "\\Users\\uploads " + User.Identity.Name + " " + User.Identity.GetUserId());
    string filePath = Path.Combine(targetPath, Server.HtmlEncode(FileUpload1.FileName));
    FileUpload1.SaveAs(filePath);
    

    【讨论】:

      【解决方案4】:

      我想您必须将代码更改为如下:

      FileUpload1.SaveAs(Server.MapPath("pathtodirectory" + FileUpload1.FileName));
      

      【讨论】:

        猜你喜欢
        • 2021-05-25
        • 2021-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 2019-12-01
        • 2016-08-04
        • 1970-01-01
        相关资源
        最近更新 更多