当前位置:网站首页>ASP. Net to access directory files outside the project website

ASP. Net to access directory files outside the project website

2022-07-04 09:33:00 Dandelion_ drq

To put it simply , It can be done by IIS The way to add a virtual directory is , When getting access paths, use HttpContext.Current.Server.MapPath("~/xxx"); The way .


Now let's talk about how to do it in detail ……

First of all to see IIS The project website structure deployed above :

 Picture description here

There are two project websites ,NewsAPI and FileAPI, Now I want to FileAPI Next visit NewsAPI Under the html Catalog .
So I am FileAPI A new one named html The virtual directory of , Point to NewsAPI Under the html Folder .

 Picture description here

Be careful :
Good configuration IIS after , Also set VS In local debugging mode , To run the code .

 Picture description here

Next is the code :

/// <summary>
///  Test whether you can access files in other project directories 
/// </summary>
/// <returns></returns>
public string Get()
{
    string str = "";

    try
    {
        string path = System.Web.HttpContext.Current.Server.MapPath("~/html/1.txt");
        StreamReader sr = new StreamReader(path, System.Text.Encoding.GetEncoding("UTF-8"));
        str = sr.ReadToEnd(); //  Read the file 
        sr.Dispose();
    }
    catch (System.Exception ex)
    {
        str = " Wrong report !" + ex.ToString();
    }

    return str;
}

It's just that the test I didn't write is very complicated , Is the use of HttpContext.Current.Server.MapPath("~/xxx"); Get the actual physical path according to the virtual directory , Then read the files in the directory and return ,path The resulting value is the physical path , So you can visit .

You can make a breakpoint to see path Value

 Picture description here

OK!~


Last , About Server.MapPath You can see the usage of this article :server.mappath()

原网站

版权声明
本文为[Dandelion_ drq]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141425122645.html

随机推荐