获取项目文件目录下的所有文件路径

时间:2021-09-14 18:45:27

WebService代码:

private void GetDirectoryFiles()
        {
            string PageURL = contextW.Request.Form["PageURL"];//URL页面
            string role_str = Utility.Tool.GetStrRole(PageURL);//在该页面的权限
            if (!string.IsNullOrEmpty(role_str))
            {
                string dir = contextW.Request.Form["dir"];
                string dirPath = contextW.Server.MapPath(dir);
                if (System.IO.Directory.Exists(dirPath))
                {
                    List<string> list = new List<string>();
                    DirectoryInfo folder = new DirectoryInfo(dirPath);
                    reGetFiles(folder, ref list, dir);

                    Jayrock.Json.JsonTextWriter writer = new Jayrock.Json.JsonTextWriter();
                    Jayrock.Json.Conversion.JsonConvert.Export(list, writer);
                    contextW.Response.Write(writer.ToString());
                }
                else
                {
                    contextW.Response.Write("0");
                }
            }
            else
            {
                contextW.Response.Write("-1");
            }
            contextW.ApplicationInstance.CompleteRequest();
        }

        //获取目录下所有的文件(递归)
        private void reGetFiles(DirectoryInfo folder, ref List<string> list,string dir)
        {
            string dirPath = contextW.Server.MapPath(dir);
            //获取此目录下的文件
            foreach (FileInfo file in folder.GetFiles())
            {
                string newPath = dir + file.FullName.Replace(dirPath, "").Replace("\\", "/");
                list.Add(newPath);
            }

            //获取此目录下的目录
            foreach (DirectoryInfo dirtemp in folder.GetDirectories())
            {
                reGetFiles(dirtemp, ref list,dir);
            }
        }

dir=“/Words/”即获取Words下所有文件相对路径