.Net Core应用程序无法将文件写入任何OSX文件夹

时间:2017-11-29 14:08:03

标签: c# .net macos asp.net-core

我正在OSX中构建一个.net核心2.0应用程序,它是一个WebAPI应用程序,当命中API端点时会创建带有虚拟数据的.xlsx。当我尝试运行它(dotnet run)时,我得到了

System.UnauthorizedAccessException: Access to the path '/Users/myuser/projects/myproject' is denied. ---> System.IO.IOException: Permission denied

我已经尝试将其作为sudo运行并更改它正在写入的文件夹而且没有帮助

// GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        CreatePackage("./");
        return "value";
    }

    public void CreatePackage(string filePath)
    {
        using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
        {
            CreateParts(package);
        }
    }

    private void CreateParts(SpreadsheetDocument document)
    {
        WorkbookPart workbookPart = document.AddWorkbookPart();
        GenerateWorkbookPartContent(workbookPart);

        WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
        GenerateWorksheetPartContent(worksheetPart);
    }

    private void GenerateWorkbookPartContent(WorkbookPart workbookPart)
    {
        Workbook workbook = new Workbook();
        workbook.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");

        Sheets sheets = new Sheets();
        Sheet sheet = new Sheet() { Name = "Sheet", SheetId = (UInt32Value)1U, Id = "rId1" };
        sheets.Append(sheet);

        workbook.Append(sheets);
        workbookPart.Workbook = workbook;
    }

    private void GenerateWorksheetPartContent(WorksheetPart worksheetPart)
    {
        Worksheet worksheet = new Worksheet();
        SheetData sheetData = new SheetData();

        Row row = new Row();
        Cell cell = new Cell() { CellReference = "A1", DataType = CellValues.InlineString };
        InlineString inlineString = new InlineString();
        Text text = new Text();
        text.Text = "hello";
        inlineString.Append(text);
        cell.Append(inlineString);
        row.Append(cell);

        sheetData.Append(row);
        worksheet.Append(sheetData);
        worksheetPart.Worksheet = worksheet;
    }

这是该类的主要部分,我正在项目文件夹中创建文件(现在)。我看到有关为CLI的所有文件提供读写权限的帖子,但这看起来并不理想。另外我看到this关于在文件上设置属性,但这是OpenXml电子表格创建方法,据我所知,它没有关于设置文件权限的任何内容(并且无论如何它都需要在文件夹中)< / p>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

我弄清楚了,我发送的文件路径是文件路径而不是文件路径,问题已解决

[HttpGet("{id}")]
public string Get(int id)
{
    CreatePackage("./testfile.xlsx");
    return "value";
}