在C#中实现文件访问的最佳方式

时间:2022-09-02 10:10:08

Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer. It is a class library contains a sub folder that contains the file. When I tried the following code in a unit test:

场景 - 我需要访问HTML模板以从我的业务逻辑层生成电子邮件。它是一个类库,包含一个包含该文件的子文件夹。当我在单元测试中尝试以下代码时:

string FilePath = string.Format(@"{0}\templates\MyFile.htm", Environment.CurrentDirectory);
string FilePath1 = string.Format(@"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory);

It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory.

它使用的是C:\ WINNT \ system32 \或ASP.NET临时文件夹目录。

What is the best to access this file without having to use an app.config or web.config file?

在不使用app.config或web.config文件的情况下访问此文件的最佳方法是什么?

[This is using a WCF Service]

[这是使用WCF服务]

4 个解决方案

#1


6  

You're running this from an ASP.Net app right? Use Server.MapPath() instead.

你是从ASP.Net应用程序运行的吗?请改用Server.MapPath()。

Also take a look at System.IO.Path.Combine() for concatenating paths.

另请参阅System.IO.Path.Combine()以连接路径。

[Edit] Since you can't use System.Web, try this:

[编辑]由于你不能使用System.Web,试试这个:

System.Reflection.Assembly.GetExecutingAssembly().Location

Or GetEntryAssembly().

#2


1  

I belive you are looking for

我相信你在寻找

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

#3


1  

I got this working on my site! I haven't been working on just this for the last 2 years!!!

我在我的网站上工作了!在过去的两年里,我一直没有做过这个!

I added this inside my system.serviceModel block of the web.config. It seems to make all the paths relative to where your service is installed.

我在web.config的system.serviceModel块中添加了这个。它似乎使所有路径都相对于您的服务安装位置。

  <system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">

better late than never?

迟到总比不到好?

#4


0  

Use

System.Web.HttpServerUtility.MapPath( "~/templates/myfile.htm" )

#1


6  

You're running this from an ASP.Net app right? Use Server.MapPath() instead.

你是从ASP.Net应用程序运行的吗?请改用Server.MapPath()。

Also take a look at System.IO.Path.Combine() for concatenating paths.

另请参阅System.IO.Path.Combine()以连接路径。

[Edit] Since you can't use System.Web, try this:

[编辑]由于你不能使用System.Web,试试这个:

System.Reflection.Assembly.GetExecutingAssembly().Location

Or GetEntryAssembly().

#2


1  

I belive you are looking for

我相信你在寻找

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

#3


1  

I got this working on my site! I haven't been working on just this for the last 2 years!!!

我在我的网站上工作了!在过去的两年里,我一直没有做过这个!

I added this inside my system.serviceModel block of the web.config. It seems to make all the paths relative to where your service is installed.

我在web.config的system.serviceModel块中添加了这个。它似乎使所有路径都相对于您的服务安装位置。

  <system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">

better late than never?

迟到总比不到好?

#4


0  

Use

System.Web.HttpServerUtility.MapPath( "~/templates/myfile.htm" )