【问题标题】:Directory.GetFiles Path IssueDirectory.GetFiles 路径问题
【发布时间】:2019-03-27 01:56:26
【问题描述】:

我一直使用Confid.VirtualDir 作为我的路径。例如:

Config.VirtualDir + "upload/gallery/image.jpg"

这给了我/upload/gallery/image.jpg的路径。例如,在每个页面中都可以正常工作:

<img style="height: 100px; " src="<%=Config.VirtualDir + "upload/gallery/image.jpg" %>" />

工作得很好。

但是现在我遇到了 Directory.GetFiles 的问题。

它适用于:

protected string[] images;
images = Directory.GetFiles(@"C:\website\mysite.com\upload\gallery", "*.jpg");

但不是:

protected string[] images;
string path = Config.VirtualDir + "upload/gallery";
images = Directory.GetFiles(path,"*.jpg");

我在控制台中没有看到任何错误。

我也尝试了"upload\gallery",但出现错误“无法识别转义序列”。

使用@"C:\website\mysite.com\upload\gallery",将暴露我的服务器的目录结构,这是我宁愿避免的。

更新:基于 Alex K. 的建议。我试过了:

protected string[] images;
protected string realImage;
    string path = Server.MapPath(@"~\upload\Gallery");
    images = Directory.GetFiles(path, "*.jpg");
    realImage = Path.Combine(Server.MapPath(@"~\upload\Gallery"), Config.VirtualDir + "upload/Gallery");

现在我很困惑如何使用 GetFiles 的路径和 realImage 路径来获取我的图像。

UPDATE2:让它工作。感谢亚历克斯 K。我在下面回答

【问题讨论】:

  • Server.MapPath() (stackoverflow.com/questions/10986525/…) 是您需要的,然后获取返回的文件名并在其前面加上您需要发送回客户端的虚拟目录。 (Path.Combine() 是最好想将文件附加到路径)
  • 谢谢,我试过 MapPath 和 PathCombine。但是现在我怎样才能从 realImage 路径中获取文件。

标签: c# asp.net


【解决方案1】:

cmets 中的描述:

代码文件:

       public List<string> images = new List<string>();
        protected string realPath;
        protected void Page_Load(object sender, EventArgs e)
        {
            string path = Server.MapPath(@"~\upload\Gallery"); 
            // this gets the actual directory path.
            realPath = Path.Combine(path, Config.VirtualDir + "upload/Gallery/");
            //this changes the path to the VirtualDir path
            DirectoryInfo di = new DirectoryInfo(path);
            //this gets file names in the folder
            foreach(var fi in di.GetFiles())
            {
                images.Add(fi.Name);
                //adds file names to images list
            }
        }

HTML:

    <img style="height: 100px; " src="<%=realPath + images[0]%>" />
    //any images[i] is accessible 

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 2011-12-09
    • 2018-05-03
    • 2017-10-02
    • 2012-02-17
    • 2011-12-27
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多