如何在不显式定义路径的情况下加载外部数据文件?
我有一个加载外部文件的 C# 程序集。该程序集由 asp.net 网站使用。 以下是加载数据文件的代码
string dataDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"data");
filePath = Path.Combine(dataDirectory,_fileName);
该组件在 Windows 应用程序中工作正常,但是当我尝试在 ASP.NET 网站中使用它时,它失败了,因为该网站找不到数据文件,它给了我以下错误:
C:\ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ Temporary ASP.NET Files \ cmictranslatorsite \ 20a8eddd \ 864b2575 \ assembly \ dl3 \ 5bd4a35e \ 8c6f79b6_98eccb01 \ data \ file.txt
I have a C# assembly that loads external files. This assembly is used by asp.net website.
The following is the code that loads the data files
string dataDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"data");
filePath = Path.Combine(dataDirectory,_fileName);
The component works fine in a windows app, but when I tried to use it in an asp.net website, it fails as the site could not find the data files, and it gives me the following error:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\cmictranslatorsite\20a8eddd\864b2575\assembly\dl3\5bd4a35e\8c6f79b6_98eccb01\data\file.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 Server.MapPath 来解析ASP.NET 应用程序中的相对物理路径。
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
正在返回C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\cmictranslatorsite\20a8eddd\864b2575 \ assembly \ dl3 \ 5bd4a35e \ 8c6f79b6_98eccb01 \ ,这是复制和执行应用程序文件的正确位置。
如果您想要一个相对于 IIS 中的虚拟目录的目录,您可以使用 Server.MapPath 来获取路径。如果您的
data
路径不是相对路径,则.config
文件可能是存储此路径的位置。在这两种情况下,请检查应用程序池身份
或您的经过身份验证的
用户是否对您正在读取或写入的路径具有适当的访问权限。You need to use Server.MapPath to resolve relative physical paths in ASP.NET applications.
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
is returningC:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\cmictranslatorsite\20a8eddd\864b2575\assembly\dl3\5bd4a35e\8c6f79b6_98eccb01\
, which is the correct place where your application files copied and executed from.If you want a directory relative to your Virtual Directory in IIS you use
Server.MapPath
to get the paths. If yourdata
path is not relative perhaps.config
file is the place to store this path. In either cases check theapp pool identity
or yourauthenticated
users have appropriate access to the path you are reading from or writing to.