2017-02-16 22 views
0

我正嘗試輸出,我在我的.NET核心API項目中的XML文件,然後訪問該文件在稍後的代碼。如何訪問copyToOutput輸出的文件?

我有我的project.json這段代碼輸出XML

"buildOptions": { 
"emitEntryPoint": true, 
    "copyToOutput": "myfile.xml" 
"preserveCompilationContext": true 
} 

然後我嘗試訪問它像這樣

public Startup(IHostingEnvironment env) 
    { 
     var path = env.ContentRootPath; 
     var filepath = Path.Combine(path, "myfile.xml"); 
     var doc = new XmlDocument(); 
     doc.Load(fileName); //throws error 
    } 

但是當我運行這個在Azure中我得到這個錯誤

FileNotFoundException - 無法找到文件 'D:\ home \ site \ wwwroot \ myfile.xml'。

我已經試過例如this answer的每個版本,但沒有運氣。

更新1

這是我Program.cs中

var host = new WebHostBuilder() 
.UseKestrel() 
.UseContentRoot(Directory.GetCurrentDirectory()) 
.UseIISIntegration() 
.UseStartup<Startup>() 
.Build(); 

主要方法我試圖通過瀏覽(與捻服務)每個能想到的文件夾,以便I'm思維來查找XML文件XML文件doesn't獲得打造出 https://myvsts.scm.azurewebsites.net/api/vfs/site/wwwroot/

更新2

我發現copyToOutput工作得很好,但在本地沒有在Azure上。我實現this瀏覽文件夾和我的xml文件不露面直到我右鍵單擊它,然後按發佈!這就像將項目發佈doesn't把它撿起來......

回答

0

看來你ContentRootPath設置爲wwwroot文件夾。通常情況下,這是設置爲包含 wwwroot文件和IHostingEnvironment.WebRootPath指向「wwwroot的」路徑的文件夾。

檢查您的Program.Main類有這樣的:

var host = new WebHostBuilder() 
    .UseContentRoot(Directory.GetCurrentDirectory()) 

此外,你可能還需要添加此文件爲「publishOptions」。 https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json#publishoptions

"publishOptions": { 
    "include": ["myfile.xml"] 
} 
+0

我不太關注你:-)我更新了我的問題。這可能是因爲xml沒有建立起來嗎? – Sturla

+0

好吧,我發現「包含」,我誤以爲。但無論瀏覽時我找不到該文件。我也試着將文件添加到另一個類庫,並設置爲copyIfNewer但仍無法找到文件... – Sturla

+0

嗯。我又添加了一條建議,儘管從更新中可以看出你已經知道了。 – natemcmaster