GetFileSystemInfos() public method

public GetFileSystemInfos ( ) : System.IO.FileSystemInfo[]
return System.IO.FileSystemInfo[]
Ejemplo n.º 1
0
 public IEnumerable<string> FileAndFolderNamesIn(string path, string searchPattern = null)
 {
     var directoryInfo = new DirectoryInfo(path);
     if (string.IsNullOrEmpty(searchPattern))
     {
         return directoryInfo.GetFileSystemInfos().Select(info => info.Name).ToList();
     }
     return directoryInfo.GetFileSystemInfos(searchPattern).Select(info => info.Name).ToList();
 }
Ejemplo n.º 2
0
        private void ImporterData(object source, System.Timers.ElapsedEventArgs e)
        {
            String FilePath = ConfigurationManager.AppSettings["ImporterService.FilePath"];
            String BakPath = ConfigurationManager.AppSettings["ImporterService.BakPath"];
            int hour = int.Parse(ConfigurationManager.AppSettings["ImporterService.hour"]);
            if (hour == DateTime.Now.Hour) {
                MasterDataBLL masterdatabll = new MasterDataBLL();
                LogBLL logbll = new LogBLL();
                DirectoryInfo mydir = new DirectoryInfo(FilePath);
                //0 SKU  1 Item 2 Customer
                FileSystemInfo[] SKUfile = mydir.GetFileSystemInfos("IIM*");
                if (SKUfile.Length > 0) {
                    ImportTxtData(0, SKUfile);
                } else {
                    int logId = logbll.InsertImportLog(0, "未找到文件", 1, 0, 0, 1);
                    logbll.InsertImportLogDetail(logId, 0, "未找到SKU文件!");
                }
                FileSystemInfo[] Itemfile = mydir.GetFileSystemInfos("HPC*");
                if (Itemfile.Length > 0) {
                    ImportTxtData(1, Itemfile);
                } else {
                    int logId = logbll.InsertImportLog(1, "未找到文件", 1, 0, 0, 1);
                    logbll.InsertImportLogDetail(logId, 0, "未找到Item文件!");
                }
                FileSystemInfo[] Customerfile = mydir.GetFileSystemInfos("RCM*");
                if (Customerfile.Length > 0) {
                    ImportTxtData(2, Customerfile);
                } else {
                    int logId = logbll.InsertImportLog(2, "未找到文件", 1, 0, 0, 1);
                    logbll.InsertImportLogDetail(logId, 0, "未找到Customer文件!");
                }

                //FileSystemInfo[] DeliveryGoods = mydir.GetFileSystemInfos("DeliveryGoods*");
                //if (DeliveryGoods.Length > 0) {
                //    ImportTxtData(3, Customerfile);
                //} else {
                //    int logId = logbll.InsertImportLog(3, "未找到文件", 1, 0, 0, 1);
                //    logbll.InsertImportLogDetail(logId, 0, "未找到Delivery Goods文件!");
                //}

                FileSystemInfo[] APHPayment = mydir.GetFileSystemInfos("APHPAY*");
                if (APHPayment.Length > 0) {
                    ImportTxtData(4, APHPayment);
                } else {
                    int logId = logbll.InsertImportLog(4, "未找到文件", 1, 0, 0, 1);
                    logbll.InsertImportLogDetail(logId, 0, "未找到APHPAY文件!");
                }

                foreach (FileSystemInfo file in mydir.GetFileSystemInfos()) {
                    File.Move(file.FullName, BakPath + file.Name);
                }
            }
        }
Ejemplo n.º 3
0
        private void Show(DirectoryInfo di, int indent)
        {
            _logger.InfoLine(string.Format($"{new String(' ', indent * 2)}{di.Name}/"));
            foreach (var dir in di.GetFileSystemInfos().OfType<DirectoryInfo>())
            {
                Show(dir, indent + 1);
            }
            var fileInfos = di.GetFileSystemInfos(Filter).OfType<FileInfo>();
            foreach (var fi in fileInfos)
            {
                string encoding = GetEncoding(fi);
                _logger.InfoLine(string.Format($"{new String(' ', indent * 2)}{fi.Name}|{fi.Length}|{encoding}"));
            }

        }
Ejemplo n.º 4
0
        //          new projectFolder
        private void openFolderButton_Click(object sender, EventArgs e)
        {
            using (var impulseFbd = new FolderBrowserDialog())
            {
                impulseResult = impulseFbd.ShowDialog();
                if (impulseResult == DialogResult.OK && !string.IsNullOrWhiteSpace(impulseFbd.SelectedPath))
                {
                    folderProject = impulseFbd.SelectedPath;
                    string[] files = Directory.GetFiles(folderProject);

                    System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
                    System.Windows.Forms.MessageBox.Show("Folder Path: " + impulseFbd.SelectedPath.ToString(), "Message");


                    System.Windows.Forms.MessageBox.Show("FolderProject:", folderProject.ToString());


                    System.IO.DirectoryInfo    di           = new System.IO.DirectoryInfo(impulseFbd.SelectedPath);
                    System.IO.FileSystemInfo[] impulseFiles = di.GetFileSystemInfos();

                    /* foreach (var impulse in impulseFiles)
                     *   System.Windows.Forms.MessageBox.Show("impulsefiles[]: " + impulse.ToString(), "Message");
                     */
                    impulseCheckedListBox1.Items.AddRange(impulseFiles);
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     复制文件夹(及文件夹下所有子文件夹和文件)
        ///		把源文件夹中的所有内容复制到目标文件夹中
        /// </summary>
        /// <param name="sourcePath">待复制的文件夹路径 如果路径不存在报异常DirectoryNotFound</param>
        /// <param name="destinationPath">目标路径 如果路径不存在则自动创建</param>
        public static void CopyDirectory(string sourcePath, string destinationPath)
        {
            var info = new DirectoryInfo(sourcePath);
            Directory.CreateDirectory(destinationPath);
            foreach (var fsi in info.GetFileSystemInfos())
            {
                var destName = Path.Combine(destinationPath, fsi.Name);

                if (fsi is FileInfo) //如果是文件,复制文件
                {
                    try
                    {
                        File.Copy(fsi.FullName, destName);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("已经存在"))
                        {
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else //如果是文件夹,新建文件夹,递归
                {
                    Directory.CreateDirectory(destName);
                    CopyDirectory(fsi.FullName, destName);
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 获取所有文件
 /// </summary>
 /// <returns></returns>
 private static List <DictionaryEntry> GetAllFiles(string dir)
 {
     try
     {
         List <DictionaryEntry> dictonary = new List <DictionaryEntry>();
         if (!System.IO.Directory.Exists(dir))
         {
             return(dictonary);
         }
         else
         {
             System.IO.DirectoryInfo    root   = new System.IO.DirectoryInfo(dir);
             System.IO.FileSystemInfo[] arrary = root.GetFileSystemInfos();
             for (int i = 0; i < arrary.Length; i++)
             {
                 dictonary.Add(new DictionaryEntry(arrary[i].FullName, arrary[i].LastWriteTime));
             }
         }
         return(dictonary);
     }
     catch (Exception ex)
     {
         // Logger.Error("获取文件夹下的所有文件" + ex.Message);
         return(null);
     }
 }
Ejemplo n.º 7
0
        public Directory_Parse(String dirname)
        {
            System.IO.DirectoryInfo    dirinfo = new System.IO.DirectoryInfo(dirname);
            System.IO.FileSystemInfo[] FSInfo  = dirinfo.GetFileSystemInfos();

            // .NET framework does not return "." and ".." directories. Let's emulate
            // the behavior.

            int added_dirs = 1; // always add "."

            if (dirinfo.Parent != null)
            {
                added_dirs = 2;                  // also add ".."
            }
            this.filenames = new String[FSInfo.Length + added_dirs];

            this.filenames[0] = ".";
            if (added_dirs == 2)
            {
                this.filenames[1] = "..";
            }

            for (int i = 0; i < FSInfo.Length; i++)
            {
                filenames[i + added_dirs] = FSInfo[i].Name;
            }

            this.current = 0;
            this.is_open = true;
        }
        private static void CopyDirectory(string sourcePath, string destinationPath)
        {
            //-----------------------------------------------------------------------
            System.IO.DirectoryInfo sourceDirectoryInfo = new System.IO.DirectoryInfo(sourcePath);

            // If the destination folder don't exist then create it
            if (!System.IO.Directory.Exists(destinationPath))
            {
                System.IO.Directory.CreateDirectory(destinationPath);
            }

            System.IO.FileSystemInfo fileSystemInfo = null;
            foreach (FileSystemInfo fileSystemInfo_loopVariable in sourceDirectoryInfo.GetFileSystemInfos())
            {
                fileSystemInfo = fileSystemInfo_loopVariable;
                string destinationFileName = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name);

                // Now check whether its a file or a folder and take action accordingly
                if (fileSystemInfo is System.IO.FileInfo)
                {
                    System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, true); Console.WriteLine(
                        FolderDifference(sourcePath, PluginFolder) + "\\" + fileSystemInfo);
                }
                else
                {
                    // Recursively call the mothod to copy all the neste folders
                    CopyDirectory(fileSystemInfo.FullName, destinationFileName);
                }
            }
        }
Ejemplo n.º 9
0
 public int FindFiles(String filename, ArrayList files, DokanFileInfo info)
 {
     string path = GetPath(filename);
     if (Directory.Exists(path))
     {
         DirectoryInfo d = new DirectoryInfo(path);
         FileSystemInfo[] entries = d.GetFileSystemInfos();
         foreach (FileSystemInfo f in entries)
         {
             FileInformation fi = new FileInformation();
             fi.Attributes = f.Attributes;
             fi.CreationTime = f.CreationTime;
             fi.LastAccessTime = f.LastAccessTime;
             fi.LastWriteTime = f.LastWriteTime;
             fi.Length = (f is DirectoryInfo) ? 0 : ((FileInfo)f).Length;
             fi.FileName = f.Name;
             files.Add(fi);
         }
         return 0;
     }
     else
     {
         return -1;
     }
 }
Ejemplo n.º 10
0
 public override void DeleteFolder(DirectoryInfo info, bool recursive)
 {
     if (!recursive && info.GetFileSystemInfos().Length != 0)
     throw new InvalidOperationException(S._("The folder {0} cannot be deleted as it is " +
      "not empty."));
        foreach (DirectoryInfo dir in info.GetDirectories())
     DeleteFolder(dir);
        foreach (FileInfo file in info.GetFiles())
     DeleteFile(file);
        for (int i = 0; i < FileNameErasePasses; ++i)
        {
     string newPath = GenerateRandomFileName(info.Parent, info.Name.Length);
     try
     {
      info.MoveTo(newPath);
     }
     catch (IOException)
     {
      Thread.Sleep(100);
      --i;
     }
        }
        info.CreationTime = info.LastWriteTime = info.LastAccessTime = MinTimestamp;
        info.Delete(true);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Tries to handle request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The WebServer.BusinessLogic.Response.
        /// </returns>
        public override Response Handle(Request request)
        {
            if (request.HttpPath.EndsWith("/"))
            {
                string path = Configurator.Instance.RelativeWwwPath + request.HttpPath.Replace("/", "\\");
                if(!Directory.Exists(path))
                {
                    return NextHandler.Handle(request);
                }
                DirectoryInfo directory = new DirectoryInfo(path);
                List<FileSystemInfo> descendants = new List<FileSystemInfo>();
                descendants.AddRange(directory.GetFileSystemInfos());

                if (descendants.Select(desc => desc.Name).Contains("index.html"))
                {
                    request.HttpPath += "index.html";
                    return NextHandler.Handle(request);
                }

                string webPage = this.CreateWebPage(descendants, request);

                Response toReturn = new Response("text/html", request.HttpVersion, Encoding.UTF8.GetBytes(webPage));
                if (Configurator.Instance.UseResponseCompression && request.AcceptEncoding == EnumAcceptEncoding.Gzip)
                {
                    toReturn.Data = GzipCompress(toReturn.Data);
                    toReturn.ContentEncoding = "gzip";
                }

                return toReturn;
            }

            return NextHandler.Handle(request);
        }
Ejemplo n.º 12
0
 //文件夹复制函数编写
 private static void CopyDirectoryAndReplaceBatFileText(string source, string destination, bool needReplace, string replaceWithText)
 {
     DirectoryInfo info = new DirectoryInfo(source);
     foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
     {
         //目标路径destName = 目标文件夹路径 + 原文件夹下的子文件(或文件夹)名字
         //Path.Combine(string a ,string b) 为合并两个字符串
         String destName = Path.Combine(destination, fsi.Name);
         //如果是文件类,就复制文件
         if (fsi is System.IO.FileInfo)
         {
             if (File.Exists(destName))
             {
                 FileAttributes fileAttributes = File.GetAttributes(destName);
                 if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                 {
                     File.SetAttributes(destName, FileAttributes.Normal);
                 }
             }
             File.Copy(fsi.FullName, destName, true);
         }
         else //如果不是 则为文件夹,继续调用文件夹复制函数,递归
         {
             Directory.CreateDirectory(destName);
             CopyDirectoryAndReplaceBatFileText(fsi.FullName, destName, needReplace, replaceWithText);
         }
     }
 }
Ejemplo n.º 13
0
        public void RefreshFilesList(string directory)
        {
            IList<FileSystemInfo> visibleThings = new List<FileSystemInfo>();
            var dir = new DirectoryInfo(directory);

            try
            {
                if (dir.ToString()!="/")
                    visibleThings.Add(dir.Parent);
                foreach (var item in dir.GetFileSystemInfos().Where(item => item.IsVisible()))
                {
                    bool b;
                    if (item.IsDirectory()) b = true; else b = txt(item.Name);
                    if (b) visibleThings.Add(item);
                }
            }
            catch (Exception ex)
            {
                Log.Error("FileListFragment", "Нет доступа к директории " + _directory.FullName + "; " + ex);
                Toast.MakeText(Activity, "Проблема доступа к директории " + directory, ToastLength.Long).Show();
                return;
            }

            _directory = dir;

            _adapter.AddDirectoryContents(visibleThings);

            ListView.RefreshDrawableState();

            Log.Verbose("FileListFragment", "Показан контент директории {0}.", directory);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 删除指定路径下的文件及文件夹
        /// </summary>
        /// <param name="path">指定路径</param>
        /// <returns>成功返回真,否则返回假</returns>
        public static bool DeleteFolder(string path)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(path);

                FileSystemInfo[] fsi = di.GetFileSystemInfos();

                foreach (FileSystemInfo tempFsi in fsi)
                {
                    if (tempFsi is DirectoryInfo)
                    {   // 删除文件夹
                        Directory.Delete(tempFsi.FullName, true);
                    }
                    else if (tempFsi is FileInfo)
                    {    // 删除文件
                        tempFsi.Delete();
                    }
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 15
0
        /// <summary> 
        /// 复制文件夹(及文件夹下所有子文件夹和文件) 
        /// </summary> 
        /// <param name="sourcePath">待复制的文件夹路径</param> 
        /// <param name="destinationPath">目标路径</param> 
        public static void CopyDirectory(String sourcePath, String destinationPath)
        {
            DirectoryInfo info = new DirectoryInfo(sourcePath);
            //   Directory.CreateDirectory(destinationPath);
            if (!Directory.Exists(destinationPath))
            {
                CreateDirectory(destinationPath);
            }
            foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
            {
                String destName = Path.Combine(destinationPath, fsi.Name);

                if (fsi is System.IO.FileInfo)          //如果是文件,复制文件
                {
                    File.Copy(fsi.FullName, destName, true);
                    FileInfo file = new FileInfo(destName);
                    file.IsReadOnly = false;
                }
                else                                    //如果是文件夹,新建文件夹,递归
                {
                    // Directory.CreateDirectory(destName);
                    CopyDirectory(fsi.FullName, destName);
                }
            }
        }
        private void ProcessFiles(string strDirectory, string strFileSpec)
        {
            var di = new DirectoryInfo(strDirectory);
            FileSystemInfo[] fis = di.GetFileSystemInfos(strFileSpec);

            // Get all files at this directory level first.
            foreach (FileSystemInfo fi in fis)
            {
                ++this.NumberOfFilesProcessed;
                if (this.Verbose)
                {
                    // From TestRectilinear, so write a blank line before next test method if there's a bunch of output
                    this.WriteLineFunc(string.Empty);
                }
                this.WriteLineFunc(string.Format("( {0} )", fi.FullName));
                ProcessFile(fi.FullName);
            }

            // Now handle recursion into subdirectories.
            if (Recursive)
            {
                // Recurse into subdirectories of this directory for files of the same spec.
                foreach (string strSubdir in Directory.GetDirectories(strDirectory))
                {
                    ProcessFiles(Path.GetFullPath(strSubdir), strFileSpec);
                }
            }
        }
        public void RefreshFilesList(string directory)
        {
            IList<FileSystemInfo> visibleThings = new List<FileSystemInfo>();
            var dir = new DirectoryInfo(directory);

            try
            {
                foreach (var item in dir.GetFileSystemInfos().Where(item => item.IsVisible()))
                {
                    visibleThings.Add(item);
                }
            }
            catch (Exception ex)
            {
                Log.Error("FileListFragment", "Couldn't access the directory " + _directory.FullName + "; " + ex);
                Toast.MakeText(Activity, "Problem retrieving contents of " + directory, ToastLength.Long).Show();
                return;
            }

            _directory = dir;

            _adapter.AddDirectoryContents(visibleThings);

            // If we don't do this, then the ListView will not update itself when then data set 
            // in the adapter changes. It will appear to the user that nothing has happened.
            ListView.RefreshDrawableState();

            Log.Verbose("FileListFragment", "Displaying the contents of directory {0}.", directory);
        }
Ejemplo n.º 18
0
        public static void UndoDirectoryCopy(DirectoryInfo source, DirectoryInfo target)
        {
            FileSystemInfo[] contents = source.GetFileSystemInfos();

            foreach (FileSystemInfo fs in contents)
            {
                if (fs is DirectoryInfo)
                {
                    DirectoryInfo dirinfo = fs as DirectoryInfo;
                    IEnumerable<DirectoryInfo> matchingInTarget = from DirectoryInfo d in target.GetDirectories()
                                                                  where d.Name == dirinfo.Name
                                                                  select d;
                    UndoDirectoryCopy(fs as DirectoryInfo, matchingInTarget.ElementAt(0));
                }
                else if (fs is FileInfo)
                {
                    FileInfo fi = fs as FileInfo;
                    IEnumerable<FileInfo> matches = from FileInfo f in target.GetFiles()
                                                    where f.Name == fi.Name
                                                    select f;
                    foreach (FileInfo file in matches)
                    {
                        file.Delete();
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private void PopulaGridCancelados()
        {
            try
            {
                sPastaProtocolos = belStaticPastas.PROTOCOLOS;
                DirectoryInfo diretorio = new DirectoryInfo(sPastaProtocolos);
                FileSystemInfo[] itens = diretorio.GetFileSystemInfos("*.xml");
                int irow = 0;
                dgvCancelamentos.Rows.Clear();
                foreach (FileSystemInfo item in itens)
                {
                    if (item.Name.Contains("ped-can"))
                    {
                        XmlDocument xml = new XmlDocument();
                        xml.Load(item.FullName);
                        dgvCancelamentos.Rows.Add();
                        dgvCancelamentos[0, irow].Value = (xml.GetElementsByTagName("infCanc").Item(0).FirstChild.InnerText == "2" ? "Homologação" : "Produção");
                        dgvCancelamentos[1, irow].Value = (xml.GetElementsByTagName("chNFe").Item(0).InnerText.Equals("") ? "S/Nota" : xml.GetElementsByTagName("chNFe").Item(0).InnerText.Substring(25, 9));
                        dgvCancelamentos[2, irow].Value = (xml.GetElementsByTagName("chNFe").Item(0).InnerText.Equals("") ? "S/Sequencia" : xml.GetElementsByTagName("chNFe").Item(0).InnerText.Substring(34, 9));
                        dgvCancelamentos[3, irow].Value = (xml.GetElementsByTagName("nProt").Item(0).InnerText.Equals("") ? "S/Protocolo" : xml.GetElementsByTagName("nProt").Item(0).InnerText);
                        dgvCancelamentos[5, irow].Value = item.Name;
                        irow++;

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 20
0
        public static FileStream CreateFile(string tempFile)
        {
            string tempPath = System.Web.HttpContext.Current.Server.MapPath("~/temp/");

            DirectoryInfo mydir = new DirectoryInfo(tempPath);
            if (mydir.Exists)
            {
                foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
                {
                    if (fsi is FileInfo)
                    {
                        try
                        {
                            FileInfo fi = (FileInfo)fsi;
                            if (fi.CreationTime < DateTime.Now.AddHours(-2))
                            {
                                fi.Delete();
                            }
                        }
                        catch { }
                    }
                }
            }
            else
            {
                mydir.Create();
            }

            return System.IO.File.Create(tempFile);
        }
Ejemplo n.º 21
0
        private static IEnumerable<Assembly> GetAssembliesInFolder(Assembly[] loadedAsms, DirectoryInfo binPath)
        {
            List<Assembly> assemblies = new List<Assembly>();
            foreach (var fileSystemInfo in binPath.GetFileSystemInfos("*.dll"))
            {
                var assemblyName = AssemblyName.GetAssemblyName(fileSystemInfo.FullName);

                //first try to load assembly from refered libraries instead of plugin 'binaries' folder
                Assembly assembly = null;
                if (loadedAsms.Any(x => x.FullName == assemblyName.FullName))
                {
                    assembly = Assembly.Load(assemblyName);
                    break;
                }

                //if not found in referenced libraries, load from plugin binaries location
                if (assembly == null)
                {
                    assembly = Assembly.LoadFile(fileSystemInfo.FullName);
                    assemblies.Add(assembly);
                }
            }

            return assemblies;
        }
Ejemplo n.º 22
0
        private void PopulaGridInutilizados()
        {
            try
            {
                DirectoryInfo diretorio = new DirectoryInfo(sPastaProtocolos);
                FileSystemInfo[] itens = diretorio.GetFileSystemInfos("*.xml");
                int irow = 0;
                dgvInutilizacoes.Rows.Clear();

                foreach (FileSystemInfo item in itens)
                {
                    if ((item.Name.Contains("_inu")) && (!item.Name.Contains("_ped_inu")))
                    {
                        XmlDocument xml = new XmlDocument();
                        xml.Load(item.FullName);
                        dgvInutilizacoes.Rows.Add();
                        dgvInutilizacoes[0, irow].Value = (xml.GetElementsByTagName("tpAmb").Item(0).InnerText == "2" ? "Homologação" : "Produção");
                        dgvInutilizacoes[1, irow].Value = xml.GetElementsByTagName("nNFIni").Item(0).InnerText.PadLeft(9, '0');
                        dgvInutilizacoes[2, irow].Value = xml.GetElementsByTagName("nNFFin").Item(0).InnerText.PadLeft(9, '0');
                        dgvInutilizacoes[3, irow].Value = Convert.ToDateTime(xml.GetElementsByTagName("dhRecbto").Item(0).InnerText).ToString("dd/MM/yyyy");
                        dgvInutilizacoes[4, irow].Value = xml.GetElementsByTagName("nProt").Item(0).InnerText;
                        irow++;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// 获取所选文件夹的文件
 /// </summary>
 /// <param name="dir"></param>
 /// <returns></returns>
 public static void GetAllFiles(DirectoryInfo dir)
 {
     List<HistoryDto> listHis = new List<HistoryDto>();
     FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();
     foreach (FileSystemInfo info in fileinfo)
     {
         if (info is DirectoryInfo)
         {
             GetAllFiles((DirectoryInfo)info);
         }
         else
         {
             var extension = info.Extension;
             if (extension.Equals(".dwg") || extension.Equals(".dwt") || extension.Equals(".dws") || extension.Equals(".dxf"))
             {
                 if (Util.GetDrwingsDto(info.Name) == null)
                 {
                     HistoryDto dto = new HistoryDto();
                     dto.Id = Guid.NewGuid().ToString();
                     dto.FileName = info.Name;
                     dto.FilePath = info.FullName.Replace("\\", "\\\\");
                     dto.FileStatus = "未处理";
                     listHis.Add(dto);
                 }
             }
         }
     }
     InsertHistory(listHis);
     listHis.Clear();
 }
Ejemplo n.º 24
0
        public void Import( string path, RouteOptions routing=RouteOptions.None,
            bool computeDependencies = false, bool computeDailyOnMidnight = false, string searchPattern = "*.*")
        {
            this.m_computeDailyDependencies = computeDailyOnMidnight;
            this.m_computeDependencies = computeDependencies;
            Console.WriteLine(path);
             DirectoryInfo di = new DirectoryInfo(path);
            FileSystemInfo[] fsinfos = di.GetFileSystemInfos(searchPattern);
            var ordered1 = fsinfos.OrderBy(f => f.CreationTime);
            Console.WriteLine("found "+ordered1.Count()+" items" );
            var ordered = ordered1.Where(f => (f.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
            Console.WriteLine("Found "+ordered.Count()+" files to import");
            foreach (var fi in ordered)
            {
                var fn = fi.FullName;

                if (fi.CreationTime.AddSeconds(2) > DateTime.Now)
                {
                    Console.WriteLine(" skipping file newer than 2 seconds ago " + fn + " " + fi.CreationTime);
                    continue;
                }
                ProcessFile(routing, fi.FullName);
            }
              // needs .net 4.0 System.Threading.Tasks.Parallel.ForEach(ordered,(fi) => ProcessFile(routing,fi));
        }
Ejemplo n.º 25
0
        public void RefreshFilesList(string directory)
        {
            IList<FileSystemInfo> visibleThings = new List<FileSystemInfo>();
            var dir = new DirectoryInfo(directory);

            try
            {
                foreach (var item in dir.GetFileSystemInfos().Where(item => Helpers.IsVisible(item)))
                {
                    visibleThings.Add(item);
                }
            }
            catch (Exception ex)
            {
                Log.Error("FileListFragment", "Couldn't access the directory " + _directory.FullName + "; " + ex);
                Toast.MakeText(Activity, "Problem retrieving contents of " + directory, ToastLength.Long).Show();
                return;
            }

            _directory = dir;

            _adapter.AddDirectoryContents(visibleThings);

            ListView.RefreshDrawableState();

            Log.Verbose("FileListFragment", "Displaying the contents of directory {0}.", directory);
        }
Ejemplo n.º 26
0
 public static string GetRandomFile(DirectoryInfo info)
 {
     FileSystemInfo[] entries = null;
        try
        {
     entries = info.GetFileSystemInfos();
        }
        catch (DirectoryNotFoundException)
        {
     return string.Empty;
        }
        if (entries.Length == 0)
     return string.Empty;
        Prng prng = PrngManager.GetInstance(ManagerLibrary.Settings.ActivePrng);
        string result = string.Empty;
        while (result.Length == 0)
        {
     int index = prng.Next(entries.Length - 1);
     if (entries[index] is DirectoryInfo)
      result = GetRandomFile((DirectoryInfo)entries[index]);
     else
      result = ((FileInfo)entries[index]).FullName;
        }
        return result;
 }
        public DataTable LoadDataInfo()
        {
            #region 加载数据信息
            image.UpFilePath = Server.MapPath(image.UpFilePath);

            DataTable dt = new DataTable("img");
            dt.Columns.Add("imgfile", Type.GetType("System.String"));

            DirectoryInfo dirinfo = new DirectoryInfo(Server.MapPath("../../images/groupicons"));
            foreach (FileSystemInfo file in dirinfo.GetFileSystemInfos())
            {
                if ((file != null) && (file.Extension != ""))
                {
                    if ((file.Extension.ToLower() == ".jpg") || (file.Extension.ToLower() == ".gif") || (file.Extension.ToLower() == ".png") || ((file.Extension.ToLower() == ".jpeg")))
                    {
                        DataRow dr = dt.NewRow();
                        dr["imgfile"] = file.Name;
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;

            #endregion
        }
Ejemplo n.º 28
0
        public static string CalculateFinalName(DirectoryInfo container, string newName)
        {
            Require.NotNull(container, "container");
            Require.NotNullOrEmpty(newName, "newName");

            if (!container.Exists)
            {
                return newName;
            }

            string ext = Path.GetExtension(newName);
            string newNameWithoutExt = newName.Substring(0, newName.Length - ext.Length);
            string finalNameWithoutExt = newNameWithoutExt;

            var infos = container.GetFileSystemInfos(ext.Length > 0 ? finalNameWithoutExt + ext : finalNameWithoutExt);
            int i = 1;

            while (infos.Length == 1)
            {
                finalNameWithoutExt = newNameWithoutExt + "(" + i + ")";

                infos = container.GetFileSystemInfos(ext.Length > 0 ? finalNameWithoutExt + ext : finalNameWithoutExt);
                ++i;
            }

            return finalNameWithoutExt + ext;
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            string source = @"C:\source";
            string target = @"E:\temp\target";
            DirectoryInfo sdi = new DirectoryInfo(source);
            foreach (FileSystemInfo item in sdi.GetFileSystemInfos())
            {
                if (Directory.Exists(item.FullName))
                {
                    if (!Directory.Exists(item.FullName + @"\.git"))
                    {
                        Console.WriteLine(item.FullName);
                        Process p = new Process();
                        p.StartInfo.FileName = "cmd.exe";
                        p.StartInfo.UseShellExecute = false;
                        p.StartInfo.RedirectStandardInput = true;
                        p.StartInfo.RedirectStandardOutput = true;
                        p.StartInfo.CreateNoWindow = true;
                        p.Start();
                        p.StandardInput.WriteLine("cd " + item.FullName);
                        p.StandardInput.WriteLine("git in");
                        p.StandardInput.WriteLine("exit");
                        p.WaitForExit(60000);
                        string s = p.StandardOutput.ReadToEnd();
                        p.Close();
                        Console.WriteLine(s);

                    }
                }
            }
        }
Ejemplo n.º 30
0
 void ProcessDirectory(DirectoryInfo dir, List<SourceFile> files)
 {
     foreach (var info in dir.GetFileSystemInfos())
     {
         if (ExcludePatterns != null && ExcludePatterns.Any(x => info.FullName.Contains(_rootDir + x)))
         {
             continue;
         }
         var f = info as FileInfo;
         if (f != null)
         {
             if (Extensions.Any(x => f.Extension.EndsWith(x)))
             {
                 files.Add(new SourceFile
                 {
                     RelativePath = f.FullName.Substring(_rootDir.Length),
                     AbsolutePath = f.FullName,
                     Contents = File.ReadAllText(f.FullName)
                 });                        
             }
         }
         else
         {
             ProcessDirectory((DirectoryInfo)info, files);                    
         }
     }
 }
Ejemplo n.º 31
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                al.Clear();
                listBox1.Items.Clear();
                txtPicPath.Text = folderBrowserDialog1.SelectedPath;//获取选定的路径
                DirectoryInfo di = new DirectoryInfo(txtPicPath.Text);
                fsinfo = di.GetFileSystemInfos();//返回目录的所有文件

                for (int i = 0; i < fsinfo.Length; i++)
                {
                    string filename = fsinfo[i].ToString();

                    string filetype = filename.Substring(filename.LastIndexOf(".") + 1, filename.Length - filename.LastIndexOf(".") - 1);
                    filetype = filetype.ToLower();//转换为小写
                    if (filetype == "jpg" || filetype == "png" || filetype == "gif" || filetype == "bmp" || filetype == "jpeg")
                    {
                        //将图片放入listbox
                        listBox1.Items.Add(fsinfo[i].ToString());
                        //将图片放入动态数组
                        al.Add(fsinfo[i].ToString());
                        flag++;
                    }
                }
                listBox1.SetSelected(0, true);
                listBox1.Focus();
                tssltotle.Text = "共有" + flag + "张图片";
                Pflag = true;
            }
            //test = txtPicPath.Text.Trim().Length;
            button2.Enabled = true;
        }
Ejemplo n.º 32
0
        private string ShowDir(string dirName, string str)
        {
            string fullName = "/templates/_shop/" + dirName;

            fullName = Server.MapPath(fullName);

            DirectoryInfo dirInfo = new DirectoryInfo(fullName);

            System.Text.StringBuilder sbhtml = new System.Text.StringBuilder("");

            foreach (FileSystemInfo subDir in dirInfo.GetFileSystemInfos())
            {
                if (subDir.GetType().Name == "DirectoryInfo")
                {
                    if (!IsShowDir(subDir)) continue;
                    sbhtml.Append("<li>" + str + "<img src=\"../images/temp02.GIF\" alt=\"�ļ���\">" + subDir.Name + "</li>");

                    sbhtml.Append(ShowDir(dirName + "/" + subDir.Name, "--" + str));
                }
                else
                {
                    if (str.Equals("")) continue;

                    if (subDir.Extension != ".htm" && subDir.Extension != ".css") continue;

                    sbhtml.Append("<li>" + str + "<img src=\"../images/temp.GIF\" alt=\"ģ��\">[<a href=\"javascript:TemplatesEdit('../../templates/_shop/" + dirName + "/" + subDir.Name + "');\">�༭</a>]");
                    sbhtml.Append("<label for=\"temp01\">" + subDir.Name + "</label></li>");
                }
            }

            return sbhtml.ToString();
        }
Ejemplo n.º 33
0
        // TODO: 可以尝试用通用版本的 GetFileNames() 加上回调函数定制出本函数
        // 获得一个子目录内的所有文件名和所有下级子目录内的文件名
        // parameters:
        //      bLastWriteTime  是否在文件名后面附加此文件的最后修改时间
        static List<string> GetFilenames(string strDir,
            bool bLastWriteTime = false,
            bool bExcludeBackupFile = true)
        {
            List<string> results = new List<string>();

            DirectoryInfo di = new DirectoryInfo(strDir);
            FileSystemInfo[] subs = di.GetFileSystemInfos();

            for (int i = 0; i < subs.Length; i++)
            {
                FileSystemInfo sub = subs[i];
                if ((sub.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    results.AddRange(GetFilenames(sub.FullName, bLastWriteTime, bExcludeBackupFile));
                    continue;
                }

                if (bExcludeBackupFile == true && FileUtil.IsBackupFile(sub.FullName) == true)
                    continue;

                if (bLastWriteTime == true)
                    results.Add(sub.FullName + "|" + DateTimeUtil.Rfc1123DateTimeStringEx(sub.LastWriteTime));
                else
                    results.Add(sub.FullName);
            }

            return results;
        }
Ejemplo n.º 34
0
        private void ImportWords_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo dinfo = new DirectoryInfo(folderBrowserDialog.SelectedPath);
                FileSystemInfo[] fsinfos = dinfo.GetFileSystemInfos();
                string ftype, temp;
                string[] r;
                int i = 0;

                foreach (FileSystemInfo fsinfo in fsinfos)
                    if (fsinfo is FileInfo)
                    {
                        ftype = Path.GetExtension(fsinfo.Name);
                        if (File.Exists(wpath + fsinfo.Name))
                        {
                            if (ftype == ".cst2")
                            {
                                temp = File.ReadAllText(wpath + fsinfo.Name, Encoding.Default);
                                temp = temp + "\r\n" + File.ReadAllText(fsinfo.FullName, Encoding.Default);

                                File.Delete(wpath + fsinfo.Name);
                                File.WriteAllText(wpath + fsinfo.Name, temp, Encoding.Default);
                                //Encoding.GetEncoding("GB2312"));
                                for (i = 0; i < Gib.cstn; ++i)
                                    if (Path.GetFileNameWithoutExtension(fsinfo.Name) == Gib.cst1[i])
                                        Gib.cst2[i] = temp;
                            }
                            if (ftype == ".cst3")
                            {
                                File.Delete(wpath + fsinfo.Name);
                                File.WriteAllText(wpath + fsinfo.Name, Gib.today.ToString());
                                for (i = 0; i < Gib.cstn; ++i)
                                    if (Path.GetFileNameWithoutExtension(fsinfo.Name) == Gib.cst1[i])
                                        Gib.cst3[i] = Gib.today;
                            }
                        }
                        else
                        {
                            File.Copy(fsinfo.FullName, wpath + fsinfo.Name);
                            if (ftype == ".cst1")
                                Gib.cst1[Gib.cstn] = Path.GetFileNameWithoutExtension(fsinfo.Name);
                            else if (ftype == ".cst2")
                                Gib.cst2[Gib.cstn] = File.ReadAllText(fsinfo.FullName, Encoding.Default);
                            else if (ftype == ".cst3")
                            {
                                Gib.cst3[Gib.cstn] = Gib.today;
                                File.WriteAllText(wpath + fsinfo.Name, Gib.today.ToString());
                            }
                            else if (ftype == ".his")
                            {
                                for (i = 0; i < 6; ++i)
                                    Gib.his[Gib.cstn, i] = 0;
                                ++Gib.cstn;
                            }
                        }
                    }
            }
        }
Ejemplo n.º 35
0
        public List <string> GetEpubFilesFromFolder(string folder)
        {
            var di    = new System.IO.DirectoryInfo(folder);
            var files = di.GetFileSystemInfos().Where(fi => fi.Extension == ".epub").Select(fi => fi.FullName).ToList();

            di.GetDirectories().ToList().ForEach(d => files.AddRange(GetEpubFilesFromFolder(d.FullName)));
            return(files);
        }
        internal static void RecursiveCount(String vPath, ref int vCount, ArrayList vFileTypes, Boolean vCancel)
        {
            if (string.IsNullOrEmpty(vPath))
            {
                return;
            }

            string currentItemName = string.Empty;

            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(vPath);


            try
            {
                foreach (FileSystemInfo fileObject in dirInfo.GetFileSystemInfos())
                {
                    if (vCancel == true)
                    {
                        break;
                    }

                    //frmMain_OnRecursiveProgressChanged();

                    if (fileObject.Attributes == FileAttributes.Directory)
                    {
                        //FileFunctions.WriteToLog("Reading Folder: " + fileObject.FullName, vWriteToLog);
                        System.Windows.Forms.Application.DoEvents();

                        // RECURSE HERE:
                        //if (fileObject.Name.ToUpper() == "SEASON 03")
                        //{
                        //    int g = 1;
                        //}
                        RecursiveCount(fileObject.FullName.ToString(CultureInfo.InvariantCulture), ref vCount, vFileTypes, vCancel);
                    }
                    else
                    {
                        currentItemName = fileObject.Name;


                        // are file types okay / appropriate
                        if (FileFunctions.IsFileTypeOK(fileObject.Name, vFileTypes))
                        {
                            vCount++;

                            Application.DoEvents();
                        } // end if file type OK
                    }     // if directory or file
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show("Error Searching files (" + currentItemName + "): " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //throw;
            }
        }
Ejemplo n.º 37
0
        private List <Result> DirectorySearch(SearchOption searchOption, Query query, string search, string searchCriteria)
        {
            var results = new List <Result>();

            var path = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(search);

            var folderList = new List <Result>();
            var fileList   = new List <Result>();

            try
            {
                var directoryInfo   = new System.IO.DirectoryInfo(path);
                var fileSystemInfos = directoryInfo.GetFileSystemInfos(searchCriteria, searchOption);

                foreach (var fileSystemInfo in fileSystemInfos)
                {
                    if ((fileSystemInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }

                    if (fileSystemInfo is System.IO.DirectoryInfo)
                    {
                        folderList.Add(resultManager.CreateFolderResult(fileSystemInfo.Name, fileSystemInfo.FullName, fileSystemInfo.FullName, query, true, false));
                    }
                    else
                    {
                        fileList.Add(resultManager.CreateFileResult(fileSystemInfo.FullName, query, true, false));
                    }
                }
            }
            catch (Exception e)
            {
                if (e is UnauthorizedAccessException || e is ArgumentException)
                {
                    results.Add(new Result {
                        Title = e.Message, Score = 501
                    });

                    return(results);
                }

#if DEBUG // Please investigate and handle error from DirectoryInfo search
                throw e;
#else
                Log.Exception($"|Flow.Launcher.Plugin.Explorer.DirectoryInfoSearch|Error from performing DirectoryInfoSearch", e);
#endif
            }

            // Intial ordering, this order can be updated later by UpdateResultView.MainViewModel based on history of user selection.
            return(results.Concat(folderList.OrderBy(x => x.Title)).Concat(fileList.OrderBy(x => x.Title)).ToList());
        }
Ejemplo n.º 38
0
 static public int GetFileSystemInfos(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         var ret = self.GetFileSystemInfos();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 39
0
 static public int GetFileSystemInfos__String__SearchOption(IntPtr l)
 {
     try {
         System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l);
         System.String           a1;
         checkType(l, 2, out a1);
         System.IO.SearchOption a2;
         checkEnum(l, 3, out a2);
         var ret = self.GetFileSystemInfos(a1, a2);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Ejemplo n.º 40
0
        static FileUploader()
        {
            //Determine the default path to upload from the local file system
            string firstCard = "";

            System.IO.DirectoryInfo    di  = new System.IO.DirectoryInfo("\\");
            System.IO.FileSystemInfo[] fsi = di.GetFileSystemInfos();

            //iterate through them
            for (int x = 0; x < fsi.Length; x++)
            {
                //check to see if this is a temporary storage card (e.g. SD card)
                if ((fsi[x].Attributes & System.IO.FileAttributes.Temporary) == System.IO.FileAttributes.Temporary)
                {
                    //if so, return the path
                    firstCard = fsi[x].FullName;
                    break;
                }
            }
            _Path        = firstCard + "\\Wockets\\";
            _HistoryPath = _Path + "kernellog\\uploadhistory\\";

            try
            {
                if (!Directory.Exists(_HistoryPath))
                {
                    Directory.CreateDirectory(_HistoryPath);
                }
            }
            catch
            {
            }
            try
            {
                DateTime now = DateTime.Now;
                _HourlyPath = _Path + "kernellog\\" + now.ToString("yyyy-MM-dd") + "\\" + now.Hour + "\\";
                if (!Directory.Exists(_HourlyPath))
                {
                    Directory.CreateDirectory(_HourlyPath);
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 41
0
        private static string GetStorageCard()
        {
            string firstCard = "";

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("\\");

            System.IO.FileSystemInfo[] fsi = di.GetFileSystemInfos();

            for (int x = 0; x < fsi.Length; x++)
            {
                if ((fsi[x].Attributes & System.IO.FileAttributes.Temporary) == System.IO.FileAttributes.Temporary)
                {
                    //if so, return the path
                    firstCard = fsi[x].FullName;
                }
            }

            return(firstCard);
        }
Ejemplo n.º 42
0
 private static void CopyFolder(string strSources, string strDest)
 {
     System.IO.DirectoryInfo    directoryInfo   = new System.IO.DirectoryInfo(strSources);
     System.IO.FileSystemInfo[] fileSystemInfos = directoryInfo.GetFileSystemInfos();
     for (int i = 0; i < fileSystemInfos.Length; i++)
     {
         System.IO.FileSystemInfo fileSystemInfo = fileSystemInfos[i];
         string text = System.IO.Path.Combine(strDest, fileSystemInfo.Name);
         if (fileSystemInfo is System.IO.FileInfo)
         {
             System.IO.File.Copy(fileSystemInfo.FullName, text, true);
         }
         else
         {
             System.IO.Directory.CreateDirectory(text);
             FileUtils.CopyFolder(fileSystemInfo.FullName, text);
         }
     }
 }
Ejemplo n.º 43
0
        public static long GetSize(string path)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
            long count = 0;

            foreach (System.IO.FileSystemInfo fi in dir.GetFileSystemInfos())
            {
                if (fi.Attributes.ToString().ToLower().Equals("directory"))
                {
                    count += GetSize(fi.FullName);
                }
                else
                {
                    System.IO.FileInfo finf = new System.IO.FileInfo(fi.FullName);
                    count += finf.Length;
                }
            }
            return(count);
        }  //录像一天4320MB 约 4.2GB 一周 30GB
Ejemplo n.º 44
0
        int obtenerÚltimoNúmeroEstadísticaEnCarpeta(string ruta)
        {
            System.IO.DirectoryInfo    di    = new System.IO.DirectoryInfo(ruta);
            System.IO.FileSystemInfo[] files = di.GetFileSystemInfos();

            int max = 0;

            //se busca el archivo con el nombre de mayor valor
            foreach (FileSystemInfo archivo in files)
            {
                int aux;
                int.TryParse(archivo.Name.Substring(0, archivo.Name.Length - archivo.Extension.Length), out aux);
                if (aux > max)
                {
                    max = aux;
                }
            }

            return(++max); //se devuelve el mayor valor de los existentes sumándole uno
        }
Ejemplo n.º 45
0
        public ArrayList GetRef(string path)
        {
            try
            {
                Dictionary <string, string> Data = new Dictionary <string, string>();

                System.IO.DirectoryInfo   di     = new System.IO.DirectoryInfo(path);
                FileSystemInfo[]          fsi    = di.GetFileSystemInfos();
                System.IO.DirectoryInfo[] folder = di.GetDirectories();

                ArrayList al = new ArrayList();

                int fileCnt = fsi.Count();

                string fileExtension = "";

                string[] oper = path.Split('\\');

                int cnt = 0;

                foreach (var item in di.GetFiles())
                {
                    fileExtension = item.Extension;

                    if (fileExtension == ".BND")
                    {
                        fileExtension = item.Name;

                        string   fileRead  = File.ReadAllText(path);
                        string[] filesplit = fileRead.Split('\n');

                        al.Add("ref");
                    }
                }
                return(al);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 46
0
        public static string GetStorageCard()
        {
            //initialize the path as an empty string
            string firstCard = "";

            System.IO.DirectoryInfo    di  = new System.IO.DirectoryInfo("\\");
            System.IO.FileSystemInfo[] fsi = di.GetFileSystemInfos();

            //iterate through them
            for (int x = 0; x < fsi.Length; x++)
            {
                //check to see if this is a temporary storage card (e.g. SD card)
                if ((fsi[x].Attributes & System.IO.FileAttributes.Temporary) == System.IO.FileAttributes.Temporary)
                {
                    //if so, return the path
                    firstCard = fsi[x].FullName;
                }
            }

            return(firstCard);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Borrar un directorio y su contenido
        /// </summary>
        public static void DeleteFolder(string fullPath)
        {
            if (System.IO.Directory.Exists(fullPath))
            {
                System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(fullPath)
                {
                    Attributes = System.IO.FileAttributes.Normal
                };

                foreach (var info in directory.GetFileSystemInfos("*", System.IO.SearchOption.AllDirectories))
                {
                    System.IO.FileInfo fInfo = info as System.IO.FileInfo;
                    if (fInfo != null)
                    {
                        info.Attributes = System.IO.FileAttributes.Normal;
                    }
                }
                System.Threading.Thread.Sleep(100);
                directory.Delete(true);
                OnFileEndHandler("Directory and files has been deleted.");
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// 指定したディレクトリ配下のファイルを全て削除する(サブディレクトリを含む)
        /// 残したいファイルのパスを指定する場合、該当ファイルは削除しない
        /// </summary>
        /// <param name="directoryPath">削除するディレクトリ</param>
        /// <param name="exceptionFilePath">残したいファイル</param>
        public static void DeleteDirectory(string directoryPath, string exceptionFilePath)
        {
            // 削除ディレクトリ情報を取得
            System.IO.DirectoryInfo delDir = new System.IO.DirectoryInfo(directoryPath);

            // サブディレクトリ内も含めすべてのファイルを取得する
            System.IO.FileSystemInfo[] fileInfos = delDir.GetFileSystemInfos("*", System.IO.SearchOption.AllDirectories);

            // 例外ファイル以外のすべてのファイル、フォルダを削除
            foreach (System.IO.FileSystemInfo fileInfo in fileInfos)
            {
                // ディレクトリまたはファイルであるかを判断する
                if ((fileInfo.Attributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)
                {
                    // ディレクトリが存在する場合、削除する
                    if (Directory.Exists(fileInfo.FullName))
                    {
                        System.IO.Directory.Delete(fileInfo.FullName, true);
                    }
                }
                else
                {
                    // ファイルの場合
                    // 例外ファイル以外の場合
                    if (fileInfo.FullName != exceptionFilePath)
                    {
                        // ファイルが存在する場合、削除する
                        if (System.IO.File.Exists(fileInfo.FullName))
                        {
                            System.IO.File.Delete(fileInfo.FullName);
                        }
                    }
                    else
                    {
                        string aa = fileInfo.FullName;
                    }
                }
            }
        }
Ejemplo n.º 49
0
 public void DelectDir(string srcPath)
 {
     try
     {
         System.IO.DirectoryInfo    dir      = new System.IO.DirectoryInfo(srcPath);
         System.IO.FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
         foreach (System.IO.FileSystemInfo i in fileinfo)
         {
             if (i is System.IO.DirectoryInfo)
             {
                 System.IO.DirectoryInfo subdir = new System.IO.DirectoryInfo(i.FullName);
                 subdir.Delete(true);          //删除子目录和文件
             }
             else
             {
                 System.IO.File.Delete(i.FullName);      //删除指定文件
             }
         }
     }
     catch (Exception e)
     {
         throw;
     }
 }
Ejemplo n.º 50
0
 public static FileSystemInfo[] GetFileSystemInfos(this DirectoryInfo dir, bool recursive)
 {
     return(dir.GetFileSystemInfos("*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
 }
Ejemplo n.º 51
0
    public static void ProcessArguments(string[] args)
    {
        //for (int i = 0; i < args.Length; i++)
        // Console.WriteLine(string.Format("{0}. {1}", i, args[i]));
        // Requires System.Configuration.Installl reference.
        var ic         = new InstallContext(null, args);
        var script     = ic.Parameters["s"];
        var action     = ic.Parameters["a"];
        var folder     = ic.Parameters["f"];
        var pattern    = ic.Parameters["p"];
        var dataFile   = ic.Parameters["d"];
        var scriptFile = new FileInfo(script);
        var scriptName = System.IO.Path.GetFileNameWithoutExtension(scriptFile.Name);

        // Show parameters
        Console.WriteLine(string.Format("Working Folder: {0}", folder));
        Console.WriteLine(string.Format("Search Pattern: {0}", pattern));
        Console.WriteLine(string.Format("Data File:      {0}", dataFile));
        Console.WriteLine(string.Format("Script Name:    {0}", scriptName));
        Console.WriteLine();
        if (string.IsNullOrEmpty(action))
        {
            // <action> <working_folder> <pattern> <data_file> <script_file_name>
            Console.WriteLine();
            Console.WriteLine("Backup or Restore Directory and File dates.");
            Console.WriteLine("");
            Console.WriteLine("    1 - Backup Dates");
            Console.WriteLine("    2 - Restore Dates");
            Console.WriteLine();
            Console.Write("Type Number or press ENTER to exit: ");
            var key = Console.ReadKey(true);
            Console.WriteLine(string.Format("{0}", key.KeyChar));
            if (key.KeyChar == '1')
            {
                action = "backup";
            }
            if (key.KeyChar == '2')
            {
                action = "restore";
            }
        }
        var currentFolder = new System.IO.DirectoryInfo(folder);
        var infos         = currentFolder.GetFileSystemInfos(pattern, System.IO.SearchOption.AllDirectories);

        if (action == "backup")
        {
            var sb    = new StringBuilder();
            var lines = new List <Line>();
            foreach (var info in infos)
            {
                var line = new Line();
                line.IsDirectory = File.GetAttributes(info.FullName).HasFlag(FileAttributes.Directory);
                if (!line.IsDirectory)
                {
                    line.Length = new FileInfo(info.FullName).Length;
                }
                // Get path relative to current folder.
                line.Created  = info.CreationTime;
                line.Modified = info.LastWriteTime;
                line.Path     = info.FullName.Substring(currentFolder.FullName.Length);
                // Skip some files.
                if (info.Name == scriptName + ".cs" || info.Name == scriptName + ".bat" || info.Name == dataFile)
                {
                    continue;
                }
                lines.Add(line);
                Console.Write(".");
            }
            var maxLength = lines.Max(x => (x.IsDirectory ? "<DIR>" : x.Length.ToString()).Length);
            foreach (var line in lines)
            {
                // Add line.
                sb.AppendFormat(
                    "{0:yyyy-MM-ddTHH:mm:ss.fffffffzzz} {1:yyyy-MM-ddTHH:mm:ss.fffffffzzz} {2," + maxLength + "} {3}\r\n",
                    line.Created, line.Modified, line.IsDirectory ? "<DIR>" : line.Length.ToString(), line.Path);
            }
            System.IO.File.WriteAllText(dataFile, sb.ToString());
        }
        else if (action == "restore")
        {
            var lines = File.ReadLines(dataFile);
            foreach (var line in lines)
            {
                var l = new Line(line);
                if (string.IsNullOrEmpty(l.Path))
                {
                    Console.WriteLine(string.Format("Is empty: '{0}'", line));
                    continue;
                }
                var path = Path.Combine(currentFolder.FullName, l.Path);
                if (!File.Exists(path) && !Directory.Exists(path))
                {
                    Console.WriteLine(string.Format("Not exist: '{0}'", line));
                    continue;
                }
                var isDirectory = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
                var fsi         = isDirectory
                                        ? (FileSystemInfo) new DirectoryInfo(path)
                                        : (FileSystemInfo) new FileInfo(path);
                var length = isDirectory ? 0L : ((FileInfo)fsi).Length;
                // Skip if size do not match
                if (length != l.Length)
                {
                    Console.WriteLine(string.Format("Wrong size: '{0}'", line));
                    continue;
                }
                try
                {
                    // Fix Last Create time.
                    if (l.Created > l.Modified)
                    {
                        l.Created = l.Modified;
                    }
                    // Restore Last Create time.
                    if (fsi.CreationTime != l.Created)
                    {
                        fsi.CreationTime = l.Created;
                    }
                    // Restore Last Write Time.
                    if (fsi.LastWriteTime != l.Modified)
                    {
                        fsi.LastWriteTime = l.Modified;
                    }
                    Console.Write(".");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        Console.WriteLine();
    }
Ejemplo n.º 52
0
 /// <summary>
 /// Returns an array of strongly typed System.IO.FileSystemInfo entries representing
 /// all the files and subdirectories in a directory.
 /// </summary>
 /// <returns>
 /// An array of strongly typed System.IO.FileSystemInfo entries.
 /// </returns>
 /// <exception cref=" <exception cref="System.IO.DirectoryNotFoundException">">
 /// The path is invalid (for example, it is on an unmapped drive).
 /// </exception>
 public FileSystemInfo[] GetFileSystemInfos()
 {
     return(_directoryInfo.GetFileSystemInfos());
 }
Ejemplo n.º 53
0
        public void FillTableForPath(string dirPath, string url, string order, System.Collections.Hashtable table)
        {
            string text = base.Request.QueryString["path"];

            text = (string.IsNullOrEmpty(text) ? "" : text);
            if (System.Text.RegularExpressions.Regex.IsMatch(text, "\\.\\."))
            {
                base.Response.Write("Access is not allowed.");
                base.Response.End();
            }
            if (text != "" && !text.EndsWith("/"))
            {
                text += "/";
            }
            string text2;
            string value;
            string text3;
            string value2;

            if (text == "")
            {
                text2  = dirPath;
                value  = url;
                text3  = "";
                value2 = "";
            }
            else
            {
                text2  = dirPath + text;
                value  = url + text;
                text3  = text;
                value2 = System.Text.RegularExpressions.Regex.Replace(text3, "(.*?)[^\\/]+\\/$", "$1");
            }
            text2 = base.Server.MapPath(text2);
            if (!System.IO.Directory.Exists(text2))
            {
                base.Response.Write("此目录不存在!" + text2);
                base.Response.End();
            }
            string[] directories = System.IO.Directory.GetDirectories(text2);
            string[] files       = System.IO.Directory.GetFiles(text2);
            switch (order)
            {
            case "uploadtime":
                System.Array.Sort(files, new FileManagerJson.DateTimeSorter(0, true));
                goto IL_268;

            case "uploadtime desc":
                System.Array.Sort(files, new FileManagerJson.DateTimeSorter(0, false));
                goto IL_268;

            case "lastupdatetime":
                System.Array.Sort(files, new FileManagerJson.DateTimeSorter(1, true));
                goto IL_268;

            case "lastupdatetime desc":
                System.Array.Sort(files, new FileManagerJson.DateTimeSorter(1, false));
                goto IL_268;

            case "photoname":
                System.Array.Sort(files, new FileManagerJson.NameSorter(true));
                goto IL_268;

            case "photoname desc":
                System.Array.Sort(files, new FileManagerJson.NameSorter(false));
                goto IL_268;

            case "filesize":
                System.Array.Sort(files, new FileManagerJson.SizeSorter(true));
                goto IL_268;

            case "filesize desc":
                System.Array.Sort(files, new FileManagerJson.SizeSorter(false));
                goto IL_268;
            }
            System.Array.Sort(files, new FileManagerJson.NameSorter(true));
IL_268:
            table["moveup_dir_path"]  = value2;
            table["current_dir_path"] = text3;
            table["current_url"]      = value;
            table["total_count"]      = directories.Length + files.Length;
            System.Collections.Generic.List <System.Collections.Hashtable> list = new System.Collections.Generic.List <System.Collections.Hashtable>();
            table["file_list"] = list;
            if (text != "")
            {
                System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
                hashtable["is_dir"]   = true;
                hashtable["has_file"] = true;
                hashtable["filesize"] = 0;
                hashtable["is_photo"] = false;
                hashtable["filetype"] = "";
                hashtable["filename"] = "";
                hashtable["path"]     = "";
                hashtable["datetime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                hashtable["filename"] = "上级目录";
                list.Add(hashtable);
            }
            for (int i = 0; i < directories.Length; i++)
            {
                System.IO.DirectoryInfo      directoryInfo = new System.IO.DirectoryInfo(directories[i]);
                System.Collections.Hashtable hashtable2    = new System.Collections.Hashtable();
                hashtable2["is_dir"]   = true;
                hashtable2["has_file"] = (directoryInfo.GetFileSystemInfos().Length > 0);
                hashtable2["filesize"] = 0;
                hashtable2["is_photo"] = false;
                hashtable2["filetype"] = "";
                hashtable2["filename"] = directoryInfo.Name;
                hashtable2["path"]     = directoryInfo.Name;
                hashtable2["datetime"] = directoryInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                list.Add(hashtable2);
            }
            for (int j = 0; j < files.Length; j++)
            {
                System.IO.FileInfo           fileInfo   = new System.IO.FileInfo(files[j]);
                System.Collections.Hashtable hashtable3 = new System.Collections.Hashtable();
                hashtable3["cid"]        = "-1";
                hashtable3["name"]       = fileInfo.Name;
                hashtable3["path"]       = url + text + fileInfo.Name;
                hashtable3["filename"]   = fileInfo.Name;
                hashtable3["filesize"]   = fileInfo.Length;
                hashtable3["addedtime"]  = fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                hashtable3["updatetime"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                hashtable3["datetime"]   = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                hashtable3["filetype"]   = fileInfo.Extension.Substring(1);
                list.Add(hashtable3);
            }
        }
Ejemplo n.º 54
0
        static int Main(string[] args)
        {
            string indentString             = "\t";
            int    spacesPerTab             = 4;
            int    maxLineWidth             = 999;
            bool   trailingCommas           = false;
            bool   spaceAfterExpandedComma  = false;
            bool   expandBetweenConditions  = true;
            bool   expandBooleanExpressions = true;
            bool   expandCaseStatements     = true;
            bool   expandCommaLists         = true;
            bool   breakJoinOnSections      = false;
            bool   uppercaseKeywords        = true;
            bool   standardizeKeywords      = true;

            bool          allowParsingErrors = false;
            bool          showUsageFriendly  = false;
            bool          showUsageError     = false;
            List <string> extensions         = new List <string>();
            bool          backups            = true;
            bool          recursiveSearch    = false;
            string        outputFileOrFolder = null;
            string        uiLangCode         = null;

            OptionSet p = new OptionSet()
                          .Add("is|indentString=", delegate(string v) { indentString = v; })
                          .Add("st|spacesPerTab=", delegate(string v) { spacesPerTab = int.Parse(v); })
                          .Add("mw|maxLineWidth=", delegate(string v) { maxLineWidth = int.Parse(v); })
                          .Add("tc|trailingCommas", delegate(string v) { trailingCommas = v != null; })
                          .Add("sac|spaceAfterExpandedComma", delegate(string v) { spaceAfterExpandedComma = v != null; })
                          .Add("ebc|expandBetweenConditions", delegate(string v) { expandBetweenConditions = v != null; })
                          .Add("ebe|expandBooleanExpressions", delegate(string v) { expandBooleanExpressions = v != null; })
                          .Add("ecs|expandCaseStatements", delegate(string v) { expandCaseStatements = v != null; })
                          .Add("ecl|expandCommaLists", delegate(string v) { expandCommaLists = v != null; })
                          .Add("bjo|breakJoinOnSections", delegate(string v) { breakJoinOnSections = v != null; })
                          .Add("uk|uppercaseKeywords", delegate(string v) { uppercaseKeywords = v != null; })
                          .Add("sk|standardizeKeywords", delegate(string v) { standardizeKeywords = v != null; })
                          .Add("ae|allowParsingErrors", delegate(string v) { allowParsingErrors = v != null; })
                          .Add("e|extensions=", delegate(string v) { extensions.Add((v.StartsWith(".") ? "" : ".") + v); })
                          .Add("r|recursive", delegate(string v) { recursiveSearch = v != null; })
                          .Add("b|backups", delegate(string v) { backups = v != null; })
                          .Add("o|outputFileOrFolder=", delegate(string v) { outputFileOrFolder = v; })
                          .Add("l|languageCode=", delegate(string v) { uiLangCode = v; })
                          .Add("h|?|help", delegate(string v) { showUsageFriendly = v != null; })
            ;

            //first parse the args
            List <string> remainingArgs = p.Parse(args);

            //then switch language if necessary
            if (uiLangCode != null)
            {
                uiLangCode = uiLangCode.ToUpperInvariant();
                if (!uiLangCode.Equals(UILANGUAGE_EN) &&
                    !uiLangCode.Equals(UILANGUAGE_FR) &&
                    !uiLangCode.Equals(UILANGUAGE_ES)
                    )
                {
                    showUsageError = true;
                    //get the resource manager with default language, before displaying error.
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedLanguageErrorMessage"));
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uiLangCode);
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    //get the resource manager AFTER setting language as requested.
                }
            }
            else
            {
                _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
            }

            //nasty trick to figure out whether we're in a pipeline or not
            bool   throwAwayValue;
            string stdInput = null;

            try
            {
                throwAwayValue = System.Console.KeyAvailable;
            }
            catch (InvalidOperationException)
            {
                Console.InputEncoding = Encoding.UTF8;
                stdInput = System.Console.In.ReadToEnd();
            }

            //then complain about missing input or unrecognized args
            if (string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 0)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("NoInputErrorMessage"));
            }
            else if ((!string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 1) || remainingArgs.Count > 1)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedArgumentsErrorMessage"));
            }

            if (extensions.Count == 0)
            {
                extensions.Add(".sql");
            }

            if (showUsageFriendly || showUsageError)
            {
                TextWriter outStream = showUsageFriendly ? Console.Out : Console.Error;
                outStream.WriteLine(_generalResourceManager.GetString("ProgramSummary"));
                outStream.WriteLine("v" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                outStream.WriteLine(_generalResourceManager.GetString("ProgramUsageNotes"));
                return(1);
            }

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                indentString,
                spacesPerTab,
                maxLineWidth,
                expandCommaLists,
                trailingCommas,
                spaceAfterExpandedComma,
                expandBooleanExpressions,
                expandCaseStatements,
                expandBetweenConditions,
                breakJoinOnSections,
                uppercaseKeywords,
                false,
                standardizeKeywords
                );

            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            bool warningEncountered = false;

            if (!string.IsNullOrEmpty(stdInput))
            {
                string    formattedOutput = null;
                bool      parsingError    = false;
                Exception parseException  = null;
                try
                {
                    formattedOutput = formattingManager.Format(stdInput, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), "STDIN"));
                    if (parseException != null)
                    {
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    }
                    warningEncountered = true;
                }
                else
                {
                    if (!string.IsNullOrEmpty(outputFileOrFolder))
                    {
                        WriteResultFile(outputFileOrFolder, null, null, ref warningEncountered, formattedOutput);
                    }
                    else
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                        Console.Out.WriteLine(formattedOutput);
                    }
                }
            }
            else
            {
                System.IO.DirectoryInfo baseDirectory = null;
                string searchPattern     = Path.GetFileName(remainingArgs[0]);
                string baseDirectoryName = Path.GetDirectoryName(remainingArgs[0]);
                if (baseDirectoryName.Length == 0)
                {
                    baseDirectoryName = ".";
                    if (searchPattern.Equals("."))
                    {
                        searchPattern = "";
                    }
                }
                System.IO.FileSystemInfo[] matchingObjects = null;
                try
                {
                    baseDirectory = new System.IO.DirectoryInfo(baseDirectoryName);
                    if (searchPattern.Length > 0)
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos(searchPattern);
                        }
                        else
                        {
                            matchingObjects = baseDirectory.GetFiles(searchPattern);
                        }
                    }
                    else
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos();
                        }
                        else
                        {
                            matchingObjects = new FileSystemInfo[0];
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("PathPatternErrorMessage"), e.Message));
                    return(2);
                }

                System.IO.StreamWriter singleFileWriter = null;
                string replaceFromFolderPath            = null;
                string replaceToFolderPath = null;
                if (!string.IsNullOrEmpty(outputFileOrFolder))
                {
                    //ignore the backups setting - wouldn't make sense to back up the source files if we're
                    // writing to another file anyway...
                    backups = false;

                    if (Directory.Exists(outputFileOrFolder) &&
                        (File.GetAttributes(outputFileOrFolder) & FileAttributes.Directory) == FileAttributes.Directory
                        )
                    {
                        replaceFromFolderPath = baseDirectory.FullName;
                        replaceToFolderPath   = new DirectoryInfo(outputFileOrFolder).FullName;
                    }
                    else
                    {
                        try
                        {
                            //let's not worry too hard about releasing this resource - this is a command-line program,
                            // when it ends or dies all will be released anyway.
                            singleFileWriter = new StreamWriter(outputFileOrFolder);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("OutputFileCreationErrorMessage"), e.Message));
                            return(3);
                        }
                    }
                }

                if (!ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, matchingObjects, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("NoFilesFoundWarningMessage"), remainingArgs[0], string.Join(",", extensions.ToArray())));
                    return(4);
                }

                if (singleFileWriter != null)
                {
                    singleFileWriter.Flush();
                    singleFileWriter.Close();
                    singleFileWriter.Dispose();
                }
            }

            if (warningEncountered)
            {
                return(5); //general "there were warnings" return code
            }
            else
            {
                return(0); //we got there, did something, and received no (handled) errors!
            }
        }
Ejemplo n.º 55
0
        private static void  matchFiles(Interp interp, string separators, string dirName, string pattern, int pIndex, TclObject resultList)
        {
            bool matchHidden;                     // True if were matching hidden file
            int  patternEnd = pIndex;             // Stores end index of the pattern
            int  dirLen     = dirName.Length;     // Caches the len of the dirName
            int  patLen     = pattern.Length;     // Caches the len of the pattern

            string[]                  dirListing; // Listing of files in dirBuf
            System.IO.FileInfo        dirObj;     // File object of dirBuf
            System.Text.StringBuilder dirBuf = new System.Text.StringBuilder();
            // Converts the dirName to string
            //   buffer or initializes it with '.'

            switch (JACL.PLATFORM)
            {
            case JACL.PLATFORM_WINDOWS:

                if (dirLen == 0)
                {
                    dirBuf.Append("./");
                }
                else
                {
                    dirBuf.Append(dirName);
                    char c = dirBuf[dirLen - 1];
                    if (((c == ':') && (dirLen == 2)) || (separators.IndexOf((System.Char)c) == -1))
                    {
                        dirBuf.Append("/");
                    }
                }

                // All comparisons should be case insensitive on Windows.

                pattern = pattern.ToLower();
                break;

            case JACL.PLATFORM_MAC:
            // Fall through to unix case--mac is not yet implemented.
            default:

                if (dirLen == 0)
                {
                    dirBuf.Append(".");
                }
                else
                {
                    dirBuf.Append(dirName);
                }
                break;
            }

            dirObj = createAbsoluteFileObj(interp, dirBuf.ToString());
            if (!System.IO.Directory.Exists(dirObj.FullName))
            {
                return;
            }

            // Check to see if the pattern needs to compare with hidden files.
            // Get a list of the directory's contents.

            if (pattern.StartsWith(".") || pattern.StartsWith("\\."))
            {
                matchHidden = true;
                // TODO tcl await only file names
                dirListing = addHiddenToDirList(dirObj);
            }
            else
            {
                matchHidden = false;
                DirectoryInfo    dirInfo   = new System.IO.DirectoryInfo(dirObj.FullName);
                FileSystemInfo[] fileInfos = dirInfo.GetFileSystemInfos();
                // TCL await only file names
                // dirListing = System.IO.Directory.GetFileSystemEntries(dirObj.FullName);
                dirListing = new string[fileInfos.Length];
                for (int x = 0; x < fileInfos.Length; x++)
                {
                    dirListing[x] = fileInfos[x].Name;
                }
            }

            // Iterate over the directory's contents.

            if (dirListing.Length == 0)
            {
                // Strip off a trailing '/' if necessary, before reporting
                // the error.

                if (dirName.EndsWith("/"))
                {
                    dirName = dirName.Substring(0, ((dirLen - 1)) - (0));
                }
            }

            // Clean up the end of the pattern and the tail pointer.  Leave
            // the tail pointing to the first character after the path
            // separator following the pattern, or NULL.  Also, ensure that
            // the pattern is null-terminated.

            if ((pIndex < patLen) && (pattern[pIndex] == '\\'))
            {
                pIndex++;
            }
            if (pIndex < (patLen - 1))
            {
                pIndex++;
            }

            for (int i = 0; i < dirListing.Length; i++)
            {
                // Don't match names starting with "." unless the "." is
                // present in the pattern.

                if (!matchHidden && (dirListing[i].StartsWith(".")))
                {
                    continue;
                }

                // Now check to see if the file matches.  If there are more
                // characters to be processed, then ensure matching files are
                // directories before calling TclDoGlob. Otherwise, just add
                // the file to the resultList.

                string tmp = dirListing[i];
                if (JACL.PLATFORM == JACL.PLATFORM_WINDOWS)
                {
                    tmp = tmp.ToLower();
                }
                if (Util.stringMatch(tmp, pattern.Substring(0, (patternEnd) - (0))))
                {
                    dirBuf.Length = dirLen;
                    dirBuf.Append(dirListing[i]);
                    if (pIndex == pattern.Length)
                    {
                        addFileToResult(interp, dirBuf.ToString(), separators, resultList);
                    }
                    else
                    {
                        dirObj = createAbsoluteFileObj(interp, dirBuf.ToString());
                        if (System.IO.Directory.Exists(dirObj.FullName))
                        {
                            dirBuf.Append("/");
                            doGlob(interp, separators, dirBuf, pattern.Substring(patternEnd + 1), resultList);
                        }
                    }
                }
            }
        }