为什么我会使用此代码“不支持URI格式”?

时间:2016-02-17 22:08:30

标签: c# reflection uri filestream

我有这个代码应该为“uripath”字符串变量指定一个字符串路径值:

private readonly FileStream _fileStream;

. . .

string uriPath = GetExecutionFolder() + "\\AppLogMsgs.txt";
_fileStream = File.OpenWrite(uriPath); 

. . .

private string GetExecutionFolder()
{
    return Path.GetDirectoryName       
(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}

...但是在尝试执行“ _fileStream = File.OpenWrite(uriPath); ”行时崩溃了。

为什么,以及我需要做些什么来纠正这种反叛的发展?

崩溃时“uriPath”的值是:

文件:\ C:\项目\ ReportScheduler \ ReportScheduler \ BIN \调试\ AppLogMsgs.txt

2 个答案:

答案 0 :(得分:3)

如果您的目的是知道包含清单 的已加载文件的位置 ,那么您可以将方法更改为

private string GetExecutionFolder()
{
    return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}

See Location Property

答案 1 :(得分:2)

AssemblyName.CodeBase属性将程序集的位置作为URL返回,并且程序集是本地文件,字符串以 file:\

开头

只需要从uriPath中移除此部分,并且应该按预期工作:

string uriPath = GetExecutionFolder() + "\\AppLogMsgs.txt";
uriPath = uriPath.Replace("file:\\", string.Empty);
_fileStream = File.OpenWrite(uriPath);