将文件上传到Azure

时间:2015-12-05 06:10:38

标签: c# azure

我想用C#.net上传一个文件,无论它是什么格式。我想检查文件是否存在。如果存在,则动态创建一个文件夹以保存上传的文件。

如何传递另一个参数来检查上传的文件是否存在,如果存在,则在Uploads文件夹中创建一个子文件夹以保存它?

public UploadedFile Upload(Stream Uploading)
{
    try
    {
        string filename = Guid.NewGuid().ToString() + ".png";
        string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Uploads"), filename);

        UploadedFile upload = new UploadedFile
        {
            FilePath = FilePath
        };

        int length = 0;
        using (FileStream writer = new FileStream(upload.FilePath, FileMode.Create))
        {
            int readCount;
            var buffer = new byte[8192];
            while ((readCount = Uploading.Read(buffer, 0, buffer.Length)) != 0)
            {
                writer.Write(buffer, 0, readCount);
                length += readCount;
            }
        }
        upload.FileLength = length;

        return new UploadedFile { FilePath = "/Uploads/" + filename };
    }
    catch (Exception ex)
    {
        _logger.Error("Error Occured in Upload", ex);
        ErrorData errorData = new ErrorData("Error Occured ", ex.Message);
        throw new WebFaultException<ErrorData>(errorData, HttpStatusCode.OK);
    }
}

1 个答案:

答案 0 :(得分:1)

在上传文件之前,请检查路径中是否存在相同的文件名。您可以使用以下代码

检查文件是否存在
y

https://msdn.microsoft.com/en-us/library/system.io.file.exists%28v=vs.110%29.aspx