[英]How to fix: Value cannot be null. Parameter name: path
我正在設置一個托管在 IIS 上的 asp.net 核心 web-api。 api 有一些用於創建 XML 文檔的邏輯,這些文檔應該直接存儲在服務器的 C: 驅動器下的文件夾中。 流程如下:
客戶端發送一個請求,該請求被處理並存儲在數據庫中。 一旦數據庫事務完成,就會生成一個帶有一些數據的 XML 文檔。 我已經在 appsettings.json 文件中存儲了應該生成這個文檔的路徑,如下所示:
"ProtocolPath": {
"PathToFolder": "C:\\some_folder"
}
在我的代碼中,我有一個類,它存儲一個 Path 變量並通過構造函數對其進行初始化:
public string Path { get; set;}
public ProtocolService(object entry, IConfiguration config)
{
_config = config;
Path = GetProtocolPath();
_entry = entry;
}
private string GetProtocolPath()
{
try
{
if(!Directory.Exists(_config.GetSection("ProtocolPath")
.GetValue<string>("PathToFolder")))
{
Directory.CreateDirectory(_config.GetSection("ProtocolPath")
.GetValue<string>("PathToFolder"));
}
StringBuilder pathBuilder = new
StringBuilder(_config.GetSection("ProtocolPath").GetValue<string>
("PathToFolder"));
pathBuilder.Append(DateTime.Now.ToString("yyyyMMdd"));
pathBuilder.Append(".xml");
return pathBuilder.ToString();
}
catch (Exception ex)
{
var msg = $"{ex.Message} : {ex.InnerException}";
Console.WriteLine(msg);
throw;
}
}
我有一些邏輯可以生成一個需要序列化為 XML 的對象。 為此,我使用了一個擴展類。
public static class XmlGenerator
{
private static FileStream _xmlFileStream;
private static XmlWriter _xmlWritter;
public static void ConvertToXml(this Protocol obj, string pathToProtocol)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(Protocol));
_xmlFileStream = new FileStream(pathToProtocol, FileMode.Append, FileAccess.Write);
_xmlWritter = XmlWriter.Create(_xmlFileStream, new XmlWriterSettings() { OmitXmlDeclaration = true, Async = true, Encoding = Encoding.UTF8 });
serializer.Serialize(_xmlWritter, obj, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
}
catch (Exception ex)
{
var msg = $"{ex.Message} : {ex.InnerException}";
Console.WriteLine(msg);
}
finally
{
_xmlWritter.Flush();
_xmlWritter.Close();
_xmlFileStream.Flush();
_xmlFileStream.Close();
}
}
}
在本地,文件夾在 C: 下正確創建,並且 XML 文件也正確生成。 但是,在托管 API 的服務器上,這一切都不會發生,日志僅顯示:
Value cannot be null.
Parameter name: path :
看起來你的GetProtocolPath()
。 pathBuilder
不返回路徑格式。
private string GetProtocolPath()
{
try
{
string path = _config.GetSection("ProtocolPath").GetValue<string>("PathToFolder");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
StringBuilder pathBuilder = new StringBuilder()
.Append(path)
.Append("\\")
.Append(DateTime.Now.ToString("yyyyMMdd"))
.Append(".xml");
return pathBuilder.ToString();
}
catch (Exception ex)
{
var msg = $"{ex.Message} : {ex.InnerException}";
Console.WriteLine(msg);
throw;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.