簡體   English   中英

使用C#下載文件並將權限設置為“所有人”,但我看到訪問被拒絕

[英]Download File in C# and set permission to Everyone but I see Access Denied

我使用ExcelLibrary,保存了一個excel文件后,我想通過WebClient下載它,我為“文件夾”設置了“完全控制”,但看到“訪問被拒絕”。

我的代碼是:

public class GenerateExcelClass
{
    System.Data.DataTable dtCustmer = new System.Data.DataTable();
    object[] query;

    public void CreateExcelClass<T>(T[] listObj, string fileName, string sheetName = "sheet")
    {
        string generatefileName = fileName + HttpContext.Current.Request.Cookies["ImenBourse"]["userId"];
        dtCustmer = ConvertToDatatable(listObj);
        DataSet ds = new DataSet("New_DataSet");
        ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
        ds.Tables.Add(dtCustmer);
        string newFilePath = HttpContext.Current.Server.MapPath(generatefileName + ".xls");
        ExcelLibrary.DataSetHelper.CreateWorkbook(newFilePath, ds);
        WebClient webClient = new WebClient();
        var path = HttpContext.Current.Server.MapPath("");
        webClient.DownloadFile(path, generatefileName + ".xls");
    }

    public static DataTable ConvertToDatatable<T>(T[] list)
    {

        PropertyInfo[] properties = list.GetType().GetElementType().GetProperties();
        DataTable dt = CreateDataTable(properties);
        if (list.Length != 0)
        {
            foreach (object o in list)
                FillData(properties, dt, o);
        }
        return dt;
    }
    private static DataTable CreateDataTable(PropertyInfo[] properties)
    {
        DataTable dt = new DataTable();
        DataColumn dc = null;
        foreach (PropertyInfo pi in properties)
        {
            DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
            dt.Columns.Add(attr.DisplayName, pi.PropertyType);
        }
        return dt;
    }
    private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
    {
        DataRow dr = dt.NewRow();
        foreach (PropertyInfo pi in properties)
        {
            DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
            if (dt.Columns.Contains(attr.DisplayName))
            {
                dr[attr.DisplayName] = pi.GetValue(o, null);
            }
        }
        dt.Rows.Add(dr);
    }
}

請嘗試一種新方法...而不是先公開真實文件,然后再公開服務器文件系統,而是將Excel文件以正確的mime類型發送到客戶端瀏覽器。

創建文件后,如果需要,可以將其保存到磁盤上的文件中,也可以使用存儲流並在響應中快速保存

指定正確的Response.ContentType =“ application / vnd.ms-excel”並將其寫入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM