Inheritance: FileSystemInfo
        /// <summary>
        /// Archives the exception report.
        /// The name of the PDF file is modified to make it easier to identify.
        /// </summary>
        /// <param name="pdfFile">The PDF file.</param>
        /// <param name="archiveDirectory">The archive directory.</param>
        public static void ArchiveException(FileInfo pdfFile, string archiveDirectory)
        {
            // Create a new subdirectory in the archive directory
            // This is based on the date of the report being archived
            DirectoryInfo di = new DirectoryInfo(archiveDirectory);
            string archiveFileName = pdfFile.Name;
            string newSubFolder = ParseFolderName(archiveFileName);
            try
            {
                di.CreateSubdirectory(newSubFolder);
            }
            catch (Exception ex)
            {
                // The folder already exists so don't create it
            }

            // Create destination path
            // Insert _EXCEPT into file name
            // This will make it easier to identify as an exception in the archive folder
            string destFileName = archiveFileName.Insert(archiveFileName.IndexOf("."), "_EXCEPT");
            string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + destFileName;

            // Move the file to the archive directory
            try
            {
                pdfFile.MoveTo(destFullPath);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 2
1
        private void WalkDirectoryTree(DirectoryInfo rootDir)
        {
            FileInfo[] files = null;
            DirectoryInfo[] dirInfo = null;
            try
            {
                files = rootDir.GetFiles("*.*");

            }
            catch (Exception e)
            {
                log.Add(e.Message);
            }

            if (files != null)
            {
                foreach (FileInfo fi in files)
                {
                    Console.WriteLine(fi.FullName);

                }

                dirInfo = rootDir.GetDirectories();
                foreach (var dir in dirInfo)
                {
                    WalkDirectoryTree(dir);
                }
            }
        }
Exemplo n.º 3
1
        public ManagedProjectReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir)
            : base(referencesResolver, parent)
        {
            if (xmlDefinition == null) {
                throw new ArgumentNullException("xmlDefinition");
            }
            if (solution == null) {
                throw new ArgumentNullException("solution");
            }
            if (tfc == null) {
                throw new ArgumentNullException("tfc");
            }
            if (gacCache == null) {
                throw new ArgumentNullException("gacCache");
            }

            XmlAttribute privateAttribute = xmlDefinition.Attributes["Private"];
            if (privateAttribute != null) {
                _isPrivateSpecified = true;
                _isPrivate = bool.Parse(privateAttribute.Value);
            }

            // determine path of project file
            string projectFile = solution.GetProjectFileFromGuid(
                xmlDefinition.GetAttribute("Project"));

            // load referenced project
            _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile);
        }
        private static bool ExtractZipArchive(string archive, string destination, FastZip fz)
        {

            DirectoryInfo newdirFI;

            if (!Directory.Exists(destination))
            {
                newdirFI = Directory.CreateDirectory(destination);

                if (!Directory.Exists(newdirFI.FullName))
                {
                    //MessageBox.Show("Directory " + destination + " could not be created.");
                    return false;
                }
            }
            else newdirFI = new DirectoryInfo(destination);


            try
            {
                Thread.Sleep(500);
                fz.ExtractZip(archive, newdirFI.FullName, "");
            }
            catch (Exception e)
            {
                Debugger.LogMessageToFile("The archive " + archive + " could not be extracted to destination " + destination +
                                          ". The following error ocurred: " + e);
            }



            return true;
        }
Exemplo n.º 5
1
        private IEnumerable<XElement> AddDirectoryAsync(DirectoryInfo dir, string collectionId, ref int count, int fnumber,
            BackgroundWorker worker)
        {
            List<XElement> addedElements = new List<XElement>();
            // добавление коллекции
            string subCollectionId;
            List<XElement> ae = this.cass.AddCollection(dir.Name, collectionId, out subCollectionId).ToList();
            if (ae.Count > 0) addedElements.AddRange(ae);

            count++;
            foreach (FileInfo f in dir.GetFiles())
            {
                if (worker.CancellationPending) break;
                if (f.Name != "Thumbs.db")
                    addedElements.AddRange(this.cass.AddFile(f, subCollectionId));
                count++;
                worker.ReportProgress(100 * count / fnumber);
            }
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                if (worker.CancellationPending) break;
                addedElements.AddRange(AddDirectoryAsync(d, subCollectionId, ref count, fnumber, worker));
            }
            return addedElements;
        }
		/// <summary>
		/// Constructs the windows content resource service.
		/// </summary>
		/// <param name="physicalBasePath">The physical base path of all resources.</param>
		/// <param name="relativeBasePath">The relative base path.</param>
		public WindowsContentResourceService(string physicalBasePath, string relativeBasePath)
		{
			// validate arguments
			if (string.IsNullOrEmpty(physicalBasePath))
				throw new ArgumentNullException("physicalBasePath");
			if (string.IsNullOrEmpty(relativeBasePath))
				throw new ArgumentNullException("relativeBasePath");

			// get the directory info
			var physicalBaseDirectory = new DirectoryInfo(physicalBasePath);
			if (!physicalBaseDirectory.Exists)
				throw new ArgumentException(string.Format("Physical base path '{0}' does not exist", physicalBaseDirectory.FullName), "physicalBasePath");

			// get the directory info
			var physicalDirectory = new DirectoryInfo(ResourceUtils.Combine(physicalBasePath, relativeBasePath));
			if (!physicalBaseDirectory.Exists)
				throw new ArgumentException(string.Format("Physical path '{0}' does not exist", physicalDirectory.FullName), "relativeBasePath");

			// check if the directory is writeable
			if (!physicalDirectory.IsWriteable())
				throw new InvalidOperationException(string.Format("Physical path '{0}' is not writeable, please check permissions", physicalDirectory.FullName));

			// set the value
			this.physicalBasePath = physicalBaseDirectory.FullName;
			this.relativeBasePath = relativeBasePath;
		}
Exemplo n.º 7
1
        public ActionResult Index()
        {
            var themes = new List<dynamic>();
            var dirbase = new DirectoryInfo(HttpContext.Server.MapPath(string.Format("~/Content/js/easyui/{0}/themes", AppSettings.EasyuiVersion)));
            DirectoryInfo[] dirs = dirbase.GetDirectories();
            foreach (var dir in dirs)
                if (dir.Name != "icons")
                    themes.Add(new {text=dir.Name,value=dir.Name });

            var navigations = new List<dynamic>();
            navigations.Add(new { text = "手风琴-2级(默认)", value = "accordion" });
            //navigations.Add(new { text = "手风琴大图标-2级", value = "accordionbigicon" });
            navigations.Add(new { text = "手风琴树", value = "accordiontree" });
            navigations.Add(new { text = "横向菜单", value = "menubutton" });
            navigations.Add(new { text = "树形结构", value = "tree" });
 
            var model = new {
                dataSource = new{
                    themes=themes,
                    navigations=navigations
                },
                form=  new sys_userService().GetCurrentUserSettings()             
            };

            return View(model);
        }
Exemplo n.º 8
1
        public static void WalkTreeDirectory(DirectoryInfo d, int depth)
        {
            try {
                FileInfo[] files = d.GetFiles();
                foreach (FileInfo file in files)
                {
                    for (int i = 0; i < depth; i++)
                        Console.Write("  ");
                    Console.WriteLine("File name: {0}, Size: {1}", file.Name, file.Length);
                }

                DirectoryInfo[] directories = d.GetDirectories();
                foreach (DirectoryInfo di in directories)
                {
                    for (int i = 0; i < depth; i++)
                        Console.Write("  ");
                    Console.WriteLine("Directory name:" + di.Name);
                    WalkTreeDirectory(di, depth + 1);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }
        }
Exemplo n.º 9
1
        /// <summary>
        /// Remove directories and files if selected
        /// </summary>
        private void BtDeleteClick(object sender, EventArgs e)
        {
            // Move CWD away as it prevents Windows OS to cleanly delete directory
            Directory.SetCurrentDirectory(App.AppHome);

            bool ret = true;
            // Depending on the selection, do the deletion:
            // 0: dont delete anythng
            // 1: delete only working files
            // 2: delete only .git tree
            // 3: delete complete repo folder

            if (_radioSelection == 1)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(_dir);
                ret = ClassUtils.DeleteFolder(dirInfo, true, true);     // Preserve .git, preserve root folder
            }

            if (_radioSelection == 2)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(_dir + Path.DirectorySeparatorChar + ".git");
                ret = ClassUtils.DeleteFolder(dirInfo, false, false);    // Remove .git, remove root folder (.git)
            }

            if(_radioSelection == 3)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(_dir);
                ret = ClassUtils.DeleteFolder(dirInfo, false, false);   // Remove .git, remove root folder
            }

            if (ret == false)
                MessageBox.Show("Some files could not be removed!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
Exemplo n.º 10
1
        public static bool CopyDirectoryTree(this DirectoryInfo source, DirectoryInfo dest)
        {
            bool wasModified = false;

            if (!Directory.Exists(dest.FullName))
                Directory.CreateDirectory(dest.FullName);

            foreach (FileInfo file in source.EnumerateFiles())
            {
                var fileDest = Path.Combine(dest.ToString(), file.Name);
                if (!File.Exists(fileDest))
                {
                    file.CopyTo(fileDest);
                    wasModified = true;
                }
            }

            foreach (DirectoryInfo subDirectory in source.GetDirectories())
            {
                var dirDest = Path.Combine(dest.ToString(), subDirectory.Name);
                DirectoryInfo newDirectory = dest.CreateSubdirectory(subDirectory.Name);
                if (CopyDirectoryTree(subDirectory, newDirectory))
                    wasModified = true;
            }

            return wasModified;
        }
        public DateTime? GetLatestUpdate()
        {
            if (_lastUpdated.HasValue) return _lastUpdated;

            var directory = new DirectoryInfo(BaseDirectory);

            var latest =
                directory.GetFiles("*.*", SearchOption.AllDirectories)
                    .OrderByDescending(f => f.LastWriteTimeUtc)
                    .FirstOrDefault();

            _lastUpdated = latest != null ? (DateTime?)latest.LastWriteTimeUtc : null;
            return _lastUpdated;
            /*
            var directory = new DirectoryInfo(BaseDirectory);

            if (!directory.Exists)
            {
                directory.Create();
                return null;
            }

            var latest =
    directory.GetFiles("*.*", SearchOption.AllDirectories)
        .OrderByDescending(f => f.LastWriteTimeUtc)
        .FirstOrDefault();

            return latest != null ? (DateTime?)latest.LastWriteTimeUtc : null;
             * */
        }
Exemplo n.º 12
1
 public BattleDetailLogger()
 {
     Directory.CreateDirectory(@"logs\battlelog");
     Staff.API("api_req_map/start").Subscribe(x => AddApi("startnext", x));
     Staff.API("api_req_map/next").Subscribe(x => AddApi("startnext", x));
     Staff.API("api_req_sortie/battleresult").Subscribe(x => AddApi("battleresult", x));
     Staff.API("api_req_combined_battle/battleresult").Subscribe(x => AddApi("battleresult", x));
     Staff.API("api_req_sortie/battle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_battle_midnight/battle").Subscribe(x => AddApi("nightbattle", x));
     Staff.API("api_req_battle_midnight/sp_midnight").Subscribe(x => AddApi("battle", x));
     //Staff.API("api_req_practice/battle").Subscribe(x => AddApi("battle", x));
     //Staff.API("api_req_practice/midnight_battle").Subscribe(x => AddApi("nightbattle", x));
     Staff.API("api_req_sortie/airbattle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_sortie/ld_airbattle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/airbattle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/battle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/midnight_battle").Subscribe(x => AddApi("nightbattle", x));
     Staff.API("api_req_combined_battle/sp_midnight").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/battle_water").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/ld_airbattle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/ec_battle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/ec_midnight_battle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/each_battle").Subscribe(x => AddApi("battle", x));
     Staff.API("api_req_combined_battle/each_battle_water").Subscribe(x => AddApi("battle", x));
     var dir = new DirectoryInfo(@"logs\battlelog");
     foreach (var file in dir.GetFiles("*.log"))
     {
         date = DateTime.Parse(Path.GetFileNameWithoutExtension(file.Name));
         if (date != DateTime.UtcNow.Date)
             CompressFile();
     }
     date = DateTime.UtcNow.Date;
 }
Exemplo n.º 13
1
        //Appends the any xml file/folder nodes onto the folder
        private void AddXmlNodes(FolderCompareObject folder, int numOfPaths, XmlDocument xmlDoc)
        {
            List<XMLCompareObject> xmlObjList = new List<XMLCompareObject>();
            List<string> xmlFolderList = new List<string>();

            for (int i = 0; i < numOfPaths; i++)
            {
                string path = Path.Combine(folder.GetSmartParentPath(i), folder.Name);

                if (Directory.Exists(path))
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(path);
                    FileInfo[] fileList = dirInfo.GetFiles();
                    DirectoryInfo[] dirInfoList = dirInfo.GetDirectories();
                    string xmlPath = Path.Combine(path, CommonXMLConstants.MetadataPath);

                    if (!File.Exists(xmlPath))
                        continue;

                    CommonMethods.LoadXML(ref xmlDoc, xmlPath);
                    xmlObjList = GetAllFilesInXML(xmlDoc);
                    xmlFolderList = GetAllFoldersInXML(xmlDoc);
                    RemoveSimilarFiles(xmlObjList, fileList);
                    RemoveSimilarFolders(xmlFolderList, dirInfoList);
                }

                AddFileToChild(xmlObjList, folder, i, numOfPaths);
                AddFolderToChild(xmlFolderList, folder, i, numOfPaths);
                xmlObjList.Clear();
                xmlFolderList.Clear();
            }
        }
Exemplo n.º 14
1
		public void LoadPlugins(string pluginPath, bool checkSubDirs)
		{
			if(!Directory.Exists(pluginPath))
				return;
			if(Plugins.Any())
				UnloadPlugins();
			var dirInfo = new DirectoryInfo(pluginPath);

			var files = dirInfo.GetFiles().Select(f => f.FullName).ToList();
			if(checkSubDirs)
			{
				foreach(var dir in dirInfo.GetDirectories())
					files.AddRange(dir.GetFiles().Select(f => f.FullName));
			}

			foreach(var file in files)
			{
				var fileInfo = new FileInfo(file);

				if(fileInfo.Extension.Equals(".dll"))
				{
					var plugins = GetModule(file, typeof(IPlugin));
					foreach(var p in plugins)
						Plugins.Add(p);
				}
			}
			Logger.WriteLine("Loading Plugins...", "PluginManager");
			LoadPluginSettings();
		}
Exemplo n.º 15
1
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = driveInfo.Name;
                    MessageBox.Show((string)item.Header);

                    if (driveInfo.IsReady)
                    {
                        DirectoryInfo dirInfo = new DirectoryInfo(driveInfo.Name);
                        foreach (DirectoryInfo di in dirInfo.GetDirectories())
                        {
                            item.Items.Add(new TreeViewItem() { Header = di.Name });
                        }
                        foreach (FileInfo fi in dirInfo.GetFiles())
                        {
                            item.Items.Add(new TreeViewItem() { Header = fi.Name });
                        }
                    }
                    this.treeView1.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemplo n.º 16
1
        public void CreateFolders(Project currentProject, string schedule, string projectName, string relativePath)
        {
            //Create a File under Properties Folder which will contain information about all WebJobs
            //https://github.com/ligershark/webjobsvs/issues/6

            // Check if the WebApp is C# or VB
            string dir = GetProjectDirectory(currentProject);
            var propertiesFolderName = "Properties";
            if (currentProject.CodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                propertiesFolderName = "My Project";
            }

            DirectoryInfo info = new DirectoryInfo(Path.Combine(dir, propertiesFolderName));

            string readmeFile = Path.Combine(info.FullName, "WebJobs.xml");

            // Copy File if it does not exit
            if (!File.Exists(readmeFile))
                AddReadMe(readmeFile);

            //Add a WebJob info to it
            XDocument doc = XDocument.Load(readmeFile);
            XElement root = new XElement("WebJob");
            root.Add(new XAttribute("Project", projectName));
            root.Add(new XAttribute("RelativePath", relativePath));
            root.Add(new XAttribute("Schedule", schedule));
            doc.Element("WebJobs").Add(root);
            doc.Save(readmeFile);
            currentProject.ProjectItems.AddFromFile(readmeFile);
        }
Exemplo n.º 17
1
        /// <summary>
        /// Dumps everything of a single type into the cache from the filesystem for BackingData
        /// </summary>
        /// <typeparam name="T">the type to get and store</typeparam>
        /// <returns>full or partial success</returns>
        public static bool LoadAllToCache(Type objectType)
        {
            if (!objectType.GetInterfaces().Contains(typeof(IData)))
                return false;

            var fileAccessor = new NetMud.DataAccess.FileSystem.BackingData();
            var typeDirectory = fileAccessor.BaseDirectory + fileAccessor.CurrentDirectoryName + objectType.Name + "/";

            if (!fileAccessor.VerifyDirectory(typeDirectory, false))
            {
                LoggingUtility.LogError(new AccessViolationException(String.Format("Current directory for type {0} does not exist.", objectType.Name)));
                return false;
            }

            var filesDirectory = new DirectoryInfo(typeDirectory);

            foreach (var file in filesDirectory.EnumerateFiles())
            {
                try
                {
                    BackingDataCache.Add(fileAccessor.ReadEntity(file, objectType));
                }
                catch(Exception ex)
                {
                    LoggingUtility.LogError(ex);
                    //Let it keep going
                }
            }

            return true;
        }
Exemplo n.º 18
1
        public void LoadTemplateData()
        {
            #region 加载模板数据

            path = Utils.GetMapPath(@"..\..\templates\");

            string templatepath = "由于目录 : ";
            string templateidlist = "0";
            foreach (DataRow dr in buildGridData().Select("valid =1"))
            {
                DirectoryInfo dirinfo = new DirectoryInfo(path + dr["directory"].ToString() + "/");
                if (dr["directory"].ToString().ToLower() == "default")
                    continue;
                if (!dirinfo.Exists)
                {
                    templatepath += dr["directory"].ToString() + " ,";
                    templateidlist += "," + dr["templateid"].ToString();
                }
            }

            if ((templateidlist != "") && (templateidlist != "0"))
            {
                base.RegisterStartupScript("", "<script>alert('" + templatepath.Substring(0, templatepath.Length - 1) + "已被删除, 因此系统将自动更新模板列表!')</script>");
                AdminTemplates.DeleteTemplateItem(templateidlist);
                AdminVistLogs.InsertLog(this.userid, this.username, this.usergroupid, this.grouptitle, this.ip, "从数据库中删除模板文件", "ID为:" + templateidlist);
                Discuz.Cache.DNTCache.GetCacheService().RemoveObject("/Forum/TemplateIDList");
                Discuz.Forum.Templates.GetValidTemplateIDList();
            }

            DataGrid1.AllowCustomPaging = false;
            DataGrid1.DataSource = buildGridData();
            DataGrid1.DataBind();

            #endregion
        }
        protected void btnupload_Click(object sender, EventArgs e)
        {
            string aud;
            aud = "Audio";

            string tempFolderAbsolutePath;
            tempFolderAbsolutePath = Server.MapPath("ShareData//");
            string subFolderRelativePath = @"Audio";//@"SubTemp1";

            DirectoryInfo tempFolder = new DirectoryInfo(tempFolderAbsolutePath);
            DirectoryInfo subFolder = tempFolder.CreateSubdirectory(subFolderRelativePath);

            string tempFileName = String.Concat(Guid.NewGuid().ToString(), @".MP3");

            string str = Path.GetExtension(FileUpload1.PostedFile.FileName);
            if ((str == ".mp3") || (str == ".wav") || (str == ".wma") || (str == ".aiff") || (str == ".au"))
            {
                FileUpload1.SaveAs(subFolder.FullName + "\\" + FileUpload1.FileName);
                SqlConnection con = new SqlConnection();
                SqlCommand cmd = new SqlCommand();
                con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\CloudTest\\Irain-M\\Irain-M\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True";
                con.Open();
                cmd.Connection = con;
                cmd.CommandText = "insert into sharedetails(filename,username,date,category) values ('" + FileUpload1.FileName + "','" + Label1.Text + "','" + DateTime.Now + "','" + aud + "')";
                cmd.ExecuteNonQuery();
                con.Close();
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp",
                               "alert('Audio uploaded successfully!'); window.location.href = 'share.aspx';", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp",
                                          "alert('This file format is not supported in this section!'); window.location.href = 'share.aspx';", true);
            }
        }
Exemplo n.º 20
1
        public static void Copy(string sourceDirectory, string targetDirectory)
        {
            DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
            DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

            CopyAll(diSource, diTarget);
        }
Exemplo n.º 21
1
 private static void CreateDirectoryIfNotExists(DirectoryInfo directoryInfo)
 {
     if(!directoryInfo.Exists) {
         CreateDirectoryIfNotExists(directoryInfo.Parent);
         directoryInfo.Create();
     }
 }
        public string GetBabylonScenes(string rootPath)
        {
            try
            {
                var dir = new DirectoryInfo(rootPath);
                var subDirs = dir.GetDirectories();
                var files = new List<JObject>();

                foreach (var directory in subDirs)
                {
                    var babylonFiles = directory.GetFiles("*.babylon");

                    if (babylonFiles.Length == 0)
                        continue;

                    foreach (var file in babylonFiles)
                    {
                        var linkName = directory.Name + "/" + Path.GetFileNameWithoutExtension(file.Name);
                        files.Add(new JObject(
                            new JProperty("url", Url.Action("Index", "BabylonJSDemo", new { demoFolderName = directory.Name, demoFile = file.Name })),
                            new JProperty("linkName", linkName)
                        ));
                    }
                }

                var json = new JObject(new JProperty("files", files));
                return json.ToString(Newtonsoft.Json.Formatting.None);
            }
            catch
            {
                var json = new JObject(new JProperty("files", ""));
                return json.ToString(Newtonsoft.Json.Formatting.None);
            }
        }
Exemplo n.º 23
1
        public static void NewlyCreatedFileDirectory()
        {
            DirectoryInfo directory = new DirectoryInfo("C:\\");
            FileInfo file = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
            Console.WriteLine("\n\nName:" + file.Name);
            Console.WriteLine("Full Name:" + file.FullName);
            Console.WriteLine("Read-Only:" + file.IsReadOnly);
            Console.WriteLine("Last Acces Time:" + file.LastAccessTime);
            Console.WriteLine("Last Write Time:" + file.LastWriteTime);
            Console.WriteLine("Length:" + file.Length);
            Console.WriteLine("Extension:" + file.Extension);
            Console.WriteLine("Attributes:" + file.Attributes);
            Console.WriteLine("Creation Time:" + file.CreationTime);
            Console.WriteLine("Directory Name: " + file.DirectoryName);

            DirectoryInfo directory1 = directory.GetDirectories().OrderByDescending(f => f.LastWriteTime).First();
            Console.WriteLine("\n\nDirectory Name:" + directory1.Name);
            Console.WriteLine("Parent:" + directory1.Parent);
            Console.WriteLine("Root:" + directory1.Root);
            Console.WriteLine("Last Write Time:" + directory1.LastWriteTime);
            Console.WriteLine("Last Access Time:" + directory1.LastAccessTime);
            Console.WriteLine("Extension:" + directory1.Extension);
            Console.WriteLine("Creation Time:" + directory1.CreationTime);
            Console.WriteLine("Attributes" + directory1.Attributes);
        }
Exemplo n.º 24
1
        public void ImportSettings(BuildType buildType)
        {
            using (new WurmAssistantGateway(AppContext.WaGatewayErrorMessage))
            {
                using (var tempDirMan = new TempDirManager())
                {
                    var tempDir = tempDirMan.GetHandle();
                    var dataDir = new DirectoryInfo(DataDirPath);

                    var tempBackupDir = new DirectoryInfo(Path.Combine(tempDir.FullName, dataDir.Name));
                    DirectoryEx.DirectoryCopyRecursive(dataDir.FullName, tempBackupDir.FullName);

                    try
                    {
                        dataDir.Delete(true);
                        var otherBuildDirPath = AppContext.GetDataDir(buildType);
                        DirectoryEx.DirectoryCopyRecursive(otherBuildDirPath, dataDir.FullName);
                    }
                    catch (Exception)
                    {
                        TransientHelper.Compensate(() => dataDir.Delete(true),
                            retryDelay: TimeSpan.FromSeconds(5));
                        TransientHelper.Compensate(() => DirectoryEx.DirectoryCopyRecursive(tempBackupDir.FullName, dataDir.FullName),
                            retryDelay: TimeSpan.FromSeconds(5));
                        throw;
                    }
                }
            }
        }
Exemplo n.º 25
1
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            lb_notvalid.Visible = false;

            if (FileUpload1.HasFile)
            {
                Guid g = Guid.NewGuid();
                DirectoryInfo updir = new DirectoryInfo(Server.MapPath("/media/upload/" + g));

                if (!updir.Exists)
                    updir.Create();

                FileUpload1.SaveAs(updir.FullName + "/" + FileUpload1.FileName);

                if (IsValidImage(updir.FullName + "/" + FileUpload1.FileName))
                {

                    tb_url.Text = "/media/upload/" + g + "/" +
                        ResizeImage(updir.FullName + "/", FileUpload1.FileName,
                        500, 1000, true);
                }
                else
                {
                    lb_notvalid.Visible = true;
                }
            }
        }
        /// <summary>
        /// Clear all the log files older than 30 Days
        /// </summary>
        /// <param name="daysToKeep">
        /// The Number of Days to Keep
        /// </param>
        public static void ClearLogFiles(int daysToKeep)
        {
            if (Directory.Exists(LogDir))
            {
                // Get all the log files
                var info = new DirectoryInfo(LogDir);
                FileInfo[] logFiles = info.GetFiles("*.txt");

                // Delete old and excessivly large files (> ~50MB).
                foreach (FileInfo file in logFiles)
                {
                    try
                    {
                        if (file.LastWriteTime < DateTime.Now.AddDays(-daysToKeep))
                        {
                            File.Delete(file.FullName);
                        }
                        else if (file.Length > 50000000)
                        {
                            File.Delete(file.FullName);
                        }
                    }
                    catch (Exception)
                    {
                        // Silently ignore files we can't delete. They are probably being used by the app right now.
                    }
                }
            }
        }
Exemplo n.º 27
1
        protected override int Run(BuildEngine engine)
        {
			foreach (ProjectInfo item in engine.Projects)
			{
				if (!String.IsNullOrEmpty(item.Properties[MSProp.SolutionDir]))
					continue;

				//To attempt to gracefully handle those those that use SolutionDir in build rules...
				string solutiondir = Path.GetDirectoryName(item.ProjectFile);
				DirectoryInfo parent = new DirectoryInfo(solutiondir);
				while (parent != null)
				{
					if (parent.GetFiles("*.sln").Length > 0)
					{
						solutiondir = parent.FullName;
						break;
					}
					parent = parent.Parent;
				}

				if (!solutiondir.EndsWith(@"\"))
					solutiondir += @"\";
				item.Properties[MSProp.SolutionDir] = solutiondir;
			}
            return 0;
        }
        public CustomizationManager(CustomizationInitializationParameters initParams)
        {
            var writeableCdfPath = CryPak.AdjustFileName(initParams.CharacterDefinitionLocation, PathResolutionRules.RealPath | PathResolutionRules.ForWriting);

            var baseCdfPath = Path.Combine(CryPak.GameFolder, initParams.BaseCharacterDefinition);
            BaseDefinition = XDocument.Load(baseCdfPath);

            if (File.Exists(writeableCdfPath))
                CharacterDefinition = XDocument.Load(writeableCdfPath);
            else
            {
                var directory = new DirectoryInfo(Path.GetDirectoryName(writeableCdfPath));
                while (!directory.Exists)
                {
                    Directory.CreateDirectory(directory.FullName);

                    directory = Directory.GetParent(directory.FullName);
                }

                File.Copy(baseCdfPath, writeableCdfPath);

                CharacterDefinition = XDocument.Load(writeableCdfPath);
            }

            InitParameters = initParams;

            Initialize();
        }
Exemplo n.º 29
0
        private void ArrangeStrings(ref string[] strs)
        {
            if (strs != null)
            {
                int len = strs.Length;

                for (int b = 0; b < len; b++)
                {
                    for (int c = 0; c < len - 1; c++)
                    {
                        string tmp1 = new DirectoryInfo(strs[c]).Name;
                        string tmp2 = new DirectoryInfo(strs[c + 1]).Name;

                        char[] splt = { '-' };

                        int v1 = int.Parse(tmp1);
                        int v2 = int.Parse(tmp2);

                        if (v1 > v2)
                        {
                            string tmp = strs[c];
                            strs[c] = strs[c + 1];
                            strs[c + 1] = tmp;

                        }

                    }
                }

            }
        }
        /// <summary>
        /// The normal PDF archival method.
        /// </summary>
        /// <param name="pdfFile">The PDF file.</param>
        /// <param name="archiveDirectory">The archive directory.</param>
        public static void ArchiveNormal(FileInfo pdfFile, string archiveDirectory)
        {
            // Create a new subdirectory in the archive directory
            // This is based on the date of the report being archived
            DirectoryInfo di = new DirectoryInfo(archiveDirectory);
            string archiveFileName = pdfFile.Name;
            string newSubFolder = ParseFolderName(archiveFileName);
            try
            {
                di.CreateSubdirectory(newSubFolder);
            }
            catch (Exception ex)
            {
                // The folder already exists so don't create it
            }

            // Create destination path
            string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + pdfFile.Name;

            // Move the file to the archive directory
            try
            {
                pdfFile.MoveTo(destFullPath);
            }
            catch (Exception ex)
            {
                // Unable to move the PDF to the archive
            }
        }
Exemplo n.º 31
0
        private void ConvertToImages(IPresentation presentation, string filename)
        {
            int i = 1;

            (this.sliderContent as Syncfusion.JavaScript.Web.Rotator).Items.Clear();

            List <string> urls     = new List <string>(4);
            string        name     = null;
            string        itemPath = "../Content/images/presentation/";

            foreach (ISlide slide in presentation.Slides)
            {
                //Converts slide to image
                System.Drawing.Image image = System.Drawing.Image.FromStream(slide.ConvertToImage(Syncfusion.Drawing.ImageFormat.Emf));
                System.Drawing.Image.GetThumbnailImageAbort myCallback =
                    new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image newImage = image.GetThumbnailImage(690, 400, myCallback, System.IntPtr.Zero);
                name = Path.GetFileNameWithoutExtension(filename);
                string dataPath = new System.IO.DirectoryInfo(Request.PhysicalPath + "..\\..\\..").FullName + "\\Content\\images\\presentation\\";

                string fileName = Path.GetFullPath(dataPath) + name;
                Directory.CreateDirectory(fileName);
                urls.Add(itemPath + name + "/" + name + i + ".jpg");
                fileName = fileName + "\\" + name + i++ + ".jpg";

                //Saves the image
                newImage.Save(fileName);
            }
            foreach (string url in urls)
            {
                Syncfusion.JavaScript.Web.RotatorItem rotatorItem = new Syncfusion.JavaScript.Web.RotatorItem();
                rotatorItem.Url     = url;
                rotatorItem.Caption = name + ".pptx";
                (this.sliderContent as Syncfusion.JavaScript.Web.Rotator).Items.Add(rotatorItem);
            }
        }
Exemplo n.º 32
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        int nID = 0;

        if (int.TryParse(hfID.Value.ToString(), out nID) && nID > 0)
        {
            DBLL.clsNews       News   = new DBLL.clsNews();
            DBLL.OptionSysDBLL option = new DBLL.OptionSysDBLL();
            bool _Result = News.update_tb_NewsBynNewsID(nID, 0, int.Parse(RadioButtonList2.SelectedValue), txtsTitle.Text, txtsAuthor.Text, "", CKEditorControl1.Text, Session["user"].ToString(), DateTime.Now, true, int.Parse(txtnSorting.Text));
            if (_Result)
            {
                string sSaveFolderFullPath = Server.MapPath(Image3.ImageUrl);
                if (File.Exists(sSaveFolderFullPath))
                {
                    //如果存在则删除
                    File.Delete(sSaveFolderFullPath);

                    System.IO.DirectoryInfo dir  = new System.IO.DirectoryInfo(sSaveFolderFullPath.Substring(0, sSaveFolderFullPath.LastIndexOf("\\")).ToString());
                    System.IO.FileInfo[]    dirs = dir.GetFiles();
                    if (dirs.Length > 0)
                    {
                        //有子文件夹
                    }
                    else
                    {
                        Directory.Delete(sSaveFolderFullPath.Substring(0, sSaveFolderFullPath.LastIndexOf("\\")).ToString());
                    }
                }
                lblsImagePath.Visible = true;
                MutileUploaderUserControl31.Visible = true;
                Label2.Visible  = false;
                Button1.Visible = false;
                Image3.Visible  = false;
            }
        }
    }
Exemplo n.º 33
0
        private void GetCurrentFiles()
        {
            var directory = new System.IO.DirectoryInfo(pickupLocation);
            var currentlyExistingFiles = directory.GetFiles("*.pdf").OrderBy(x => x.Name);

            foreach (var file in currentlyExistingFiles)
            {
                try
                {
                    if (file.Length < 10)
                    {
                        logger.Info($"Bad file {file.Name}.  Moving to bad scan folder.");
                        MoveFileToBadScans(file);
                    }

                    logger.Debug($"Pickup file {file}");
                    newFileQueue.Enqueue(file);
                }
                catch (Exception ex)
                {
                    logger.Error($"Error picking up file: {file.FullName}.  Exception: {ex}");
                }
            }
        }
Exemplo n.º 34
0
        /// <summary>
        ///
        /// </summary>
        private void CheckRemoveOldFiles()
        {
            System.IO.DirectoryInfo       dinfo    = new System.IO.DirectoryInfo(mLogDirector);
            Dictionary <DateTime, string> logFiles = new Dictionary <DateTime, string>();

            if (dinfo.Exists)
            {
                foreach (var vv in dinfo.EnumerateFileSystemInfos())
                {
                    string   sfileName = vv.Name;
                    DateTime dt        = new DateTime(int.Parse(sfileName.Substring(0, 4)), int.Parse(sfileName.Substring(4, 2)), int.Parse(sfileName.Substring(6, 2)), int.Parse(sfileName.Substring(8, 2)), int.Parse(sfileName.Substring(10, 2)), int.Parse(sfileName.Substring(12, 2)));
                    logFiles.Add(dt, vv.FullName);
                }
            }


            if (logFiles.Count > 9)
            {
                foreach (var vv in logFiles.OrderBy(e => e.Key).Take(5))
                {
                    if (System.IO.File.Exists(vv.Value))
                    {
                        try
                        {
                            if (System.IO.File.GetAttributes(vv.Value) != FileAttributes.ReadOnly)
                            {
                                System.IO.File.Delete(vv.Value);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Exemplo n.º 35
0
        private void btnZipFolder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFolder.Text))
            {
                MessageBox.Show("Please select your folder", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFolder.Focus();
                return;
            }
            string path   = txtFolder.Text;
            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
                    zip.AddDirectory(path);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
                    zip.SaveProgress          += Zip_SaveProgress;
                    zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName, di.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
Exemplo n.º 36
0
        // - ALMOST OK -
        //Send a list of the files with a given folder path
        public static void ListFiles(string location)
        {
            string files = "";

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(location);
            FileInfo[] file             = dir.GetFiles("*.*");
            if (file.Length != 0)
            {
                foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
                {
                    files = files + "\n" + f.Name + " | " + f.Length.ToString() + " bytes";
                }
                byte[] Packet = Encoding.ASCII.GetBytes(files);
                Writer.Write(Packet, 0, Packet.Length);
                Writer.Flush();
            }
            else
            {
                files = "no files here...";
                byte[] Packet = Encoding.ASCII.GetBytes(files);
                Writer.Write(Packet, 0, Packet.Length);
                Writer.Flush();
            }
        }
Exemplo n.º 37
0
        private static List <List <SoundAtom> > getFolderOto(System.IO.DirectoryInfo dir, System.IO.DirectoryInfo basedir, List <string> callbackHashTable)
        {
            List <List <SoundAtom> > ret = new List <List <SoundAtom> >();

            FileInfo[] otofile = dir.GetFiles("oto.ini");
            foreach (FileInfo fi in otofile)
            {
                List <SoundAtom> otolist = getOto(fi, basedir);
                callbackHashTable.Add(PathUtils.RelativePath(basedir.FullName, fi.FullName));
                ret.Add(otolist);
            }
            DirectoryInfo[] dis    = dir.GetDirectories();
            Object          locker = new Object();

            Parallel.For(0, dis.Length, (i) => {
                DirectoryInfo di            = dis[i];
                List <List <SoundAtom> > fs = getFolderOto(di, basedir, callbackHashTable);
                lock (locker)
                {
                    ret.AddRange(fs.ToArray());
                }
            });
            return(ret);
        }
Exemplo n.º 38
0
        public static ArrayList listarArchivosIn(string origen, DateTime fechaUltimoIngreso, DateTime fechaUltimaCopia, String Formato, String Prefijo, string destino)
        {
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(origen);


            // Get the files in the directory and print out some information about them.
            System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
            ArrayList            lista     = new ArrayList();

            foreach (System.IO.FileInfo fi in fileNames)
            {
                string ultimoingreso   = fi.LastAccessTime.ToString();
                string ultimoescritura = fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm:ss");

                if (Convert.ToDateTime(ultimoescritura) > fechaUltimaCopia && fi.Name.Contains(Formato) && fi.Name.Contains(Prefijo))
                {
                    //lista.Add(fi.Name);
                    lista.Add(fi.LastWriteTime);
                    fi.CopyTo(destino + fi.Name, true);
                    //fi.CopyTo(destino + fi.Name.Substring(0,3) + DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()+".TXT", true);
                }
            }
            return(lista);
        }
Exemplo n.º 39
0
    static void QueryDuplicates2()
    {
        // Change the root drive or folder if necessary.
        string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\Common7";

        // Make the lines shorter for the console display
        int charsToSkip = startFolder.Length;

        // Take a snapshot of the file system.
        System.IO.DirectoryInfo          dir      = new System.IO.DirectoryInfo(startFolder);
        IEnumerable <System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

        // Note the use of a compound key. Files that match
        // all three properties belong to the same group.
        // A named type is used to enable the query to be
        // passed to another method. Anonymous types can also be used
        // for composite keys but cannot be passed across method boundaries
        //
        var queryDupFiles =
            from file in fileList
            group file.FullName.Substring(charsToSkip) by
            new PortableKey
        {
            Name = file.Name, LastWriteTime = file.LastWriteTime, Length = file.Length
        }

        into fileGroup
        where fileGroup.Count() > 1
        select fileGroup;

        var list = queryDupFiles.ToList();

        int i = queryDupFiles.Count();

        PageOutput <PortableKey, string>(queryDupFiles);
    }
Exemplo n.º 40
0
        private void button4_Click(object sender, EventArgs e)
        {
            //string path = @"c:\temp\MyTest.txt";

            string path1 = AppDomain.CurrentDomain.BaseDirectory + @"Data" + "\\" + DateTime.Now.ToString("yyyy-MM-dd");

            System.IO.DirectoryInfo info1 = System.IO.Directory.CreateDirectory(path1);
            string path = path1 + "\\" + "1.txt";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            string[] hv_mat2d = { "Sx", "Sy", "Phi", "theta", "Tx", "Ty", "Mat2d" };

            using (FileStream fs = File.Create(path))
            {
                for (int i = 0; i < 6; i++)
                {
                    byte[] info = new UTF8Encoding(true).GetBytes(hv_mat2d[i] + "=" + Result[i].ToString() + "  ");
                    fs.Write(info, 0, info.Length);
                }
            }
        }
Exemplo n.º 41
0
        private void addFolder(System.IO.DirectoryInfo directoryInfo, TreeNodeCollection nodes)
        {
            foreach (var directory in directoryInfo.GetDirectories())
            {
                String   imageKey = "folder";
                TreeNode node     = nodes.Add(directory.FullName, directory.Name, imageKey, imageKey);
                addFolder(directory, node.Nodes);
            }

            foreach (var file in directoryInfo.GetFiles())
            {
                String imageKey = "file";
                String key      = file.Extension;
                if (!String.IsNullOrEmpty(key) && key.Length > 0)
                {
                    key = key.Substring(1);
                    if (ilFileIcon.Images.ContainsKey(key))
                    {
                        imageKey = key;
                    }
                }
                nodes.Add(file.FullName, file.Name, imageKey, imageKey);
            }
        }
Exemplo n.º 42
0
        public ActionResult FileTreeFolders(string dir)
        {
            if (string.IsNullOrEmpty(dir))
            {
                dir = "/";
            }

            if (!dir.StartsWith(ConfigHelper.FileManagerRoot))
            {
                return(new HttpStatusCodeResult(403, "Cannot access this directory"));
            }

            DirectoryInfo di     = new System.IO.DirectoryInfo(Server.MapPath(dir));
            var           output = di.GetDirectories()
                                   .OrderBy(cdi => cdi.Name)
                                   .Select(cdi => new
            {
                data  = new { title = cdi.Name },
                state = "closed",
                attr  = new { title = dir + cdi.Name + "/" }
            }).ToArray();

            return(Json(output, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 43
0
        /// <summary>
        /// Internal method for executing a resultless search
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="searchPattern"></param>
        /// <param name="searchHiddenFilesAndFolders"></param>
        private void FindFiles(System.IO.DirectoryInfo directory, string searchPattern, bool searchHiddenFilesAndFolders)
        {
            string[] searchPatterns = searchPattern.Split(new char[] { ';', '|' });

            foreach (string pattern in searchPatterns)
            {
                if (pattern == null)
                {
                    continue;
                }

                FileInfo[] files = directory.GetFiles(pattern);

                foreach (FileInfo file in files)
                {
                    if (Searching.IsFileOrFolderHidden(file) && !searchHiddenFilesAndFolders)
                    {
                        continue;
                    }

                    this.OnFileFound(this, new SearchEventArgs(file));
                }
            }
        }
Exemplo n.º 44
0
        public static bool IsEmptyDirectory(string dirPath)
        {
            if (Directory.Exists(dirPath) == false)
            {
                return(false);
            }            // else

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

            DirectoryInfo[] dirList = dirInfo.GetDirectories();

            FileInfo[] fileList = dirInfo.GetFiles();

            if (dirList.HasValue())
            {
                return(false);
            }
            if (fileList.HasValue())
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 45
0
        /// <summary>
        /// 古いログ情報を削除する
        /// </summary>
        public void DeleteOldFile()
        {
            if (_config.FileDeleteDayPoint == -1)
            {
                return; // ファイル削除しない
            }

            DateTime DelDateTime = DateTime.Now.AddDays(-_config.FileDeleteDayPoint);    // 例えば3日前以上のファイルを削除する。など

            //"C:\test"以下のファイルをすべて取得する
            System.IO.DirectoryInfo          di    = new System.IO.DirectoryInfo(_config.LogDirPath);
            IEnumerable <System.IO.FileInfo> files =
                di.EnumerateFiles("*" + _config.LogFileName + "*", System.IO.SearchOption.AllDirectories);

            //ファイルを列挙する
            foreach (System.IO.FileInfo f in files)
            {
                if (f.LastWriteTime < DelDateTime)
                {
                    // ファイルを削除する
                    f.Delete();
                }
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// 多线程批量创建索引(要求是统一的sourceflag,即目录是一致的)
        /// </summary>
        /// <param name="list">sourceflag统一的</param>
        /// <param name="pathSuffix">索引目录后缀,加在电商的路径后面,为空则为根目录.如sa\1</param>
        /// <param name="isCreate">默认为false 增量索引  true的时候删除原有索引</param>
        public void BuildIndexMutiThread <T>(List <T> list, string rootIndexPath, bool isCreate = false)
        {
            if (list == null || list.Count == 0)
            {
                return;
            }

            System.IO.DirectoryInfo dirInfo   = System.IO.Directory.CreateDirectory(rootIndexPath);
            FSDirectory             directory = FSDirectory.Open(dirInfo);

            using (IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), isCreate, IndexWriter.MaxFieldLength.LIMITED))
            {
                writer.SetMaxBufferedDocs(100); //控制写入一个新的segent前内存中保存的doc的数量 默认10
                writer.MergeFactor     = 100;   //控制多个segment合并的频率,默认10
                writer.UseCompoundFile = true;  //创建复合文件 减少索引文件数量

                foreach (var item in list)
                {
                    Document document = getDocument(item);
                    writer.AddDocument(document);
                }
                //  writer.Optimize();//优化,合并 (多线程创建索引的时候不做优化合并,Merge的时候处理)
            }
        }
        /*Get FilePath key from app.config
         * Returns randomly selected image from folder*/
        private static string GetImageFolderFromConfig()
        {
            const string FILE_KEY_NAME = "FilePath";
            var          appSettings   = ConfigurationManager.AppSettings;
            Random       rnd           = new Random();

            //Check if app settings isn't working
            if (appSettings.Count == 0)
            {
                Console.WriteLine("App settings empty");
                throw new System.IO.FileNotFoundException("Nothing in App Settings file");
            }

            System.IO.DirectoryInfo direct = new System.IO.DirectoryInfo(appSettings[FILE_KEY_NAME]);

            var files   = GetFilesByExtensions(direct, ".jpg", ".png");
            int randNum = rnd.Next(1, files.Count());

            var randomFileName = files.ElementAt(randNum);

            Console.WriteLine("Chosen file name : " + randomFileName);

            return(appSettings[FILE_KEY_NAME] + "\\" + randomFileName);
        }
Exemplo n.º 48
0
        private void folderOpen_Click(object sender, EventArgs e)
        {
            folderList.Items.Clear();
            var directory = txtFolderName.Text;
            var x         = new System.IO.DirectoryInfo(directory);

            try{
                folderList.Items.AddRange(x.GetFiles("*"));
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("指定されたフォルダが見つかりません");
                return;
            }


            //指定フォルダ以下のファイルをすべて取得する
            files = System.IO.Directory.GetFiles
                    (
                txtFolderName.Text,
                "*",
                System.IO.SearchOption.AllDirectories
                    );
        }
Exemplo n.º 49
0
        public DirectoryInfo[] GetDirectories()
        {
            List <DirectoryInfo> dirs = new List <DirectoryInfo>();

            try
            {
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(NameFix.AddLongPathPrefix(FullName));
                if (!di.Exists)
                {
                    return(dirs.ToArray());
                }

                System.IO.DirectoryInfo[] arrDi = di.GetDirectories();
                foreach (System.IO.DirectoryInfo tDi in arrDi)
                {
                    try
                    {
                        DirectoryInfo lDi = new DirectoryInfo
                        {
                            Name     = tDi.Name,
                            FullName = Path.Combine(FullName, tDi.Name)
                        };
                        try { lDi.LastWriteTime = tDi.LastWriteTimeUtc.Ticks; } catch { lDi.LastWriteTime = 0; }
                        try { lDi.LastAccessTime = tDi.LastAccessTimeUtc.Ticks; } catch { lDi.LastWriteTime = 0; }
                        try { lDi.CreationTime = tDi.CreationTimeUtc.Ticks; } catch { lDi.LastWriteTime = 0; }

                        dirs.Add(lDi);
                    }
                    catch { }
                }
            }
            catch
            {
            }
            return(dirs.ToArray());
        }
Exemplo n.º 50
0
        // Picks up files extracted from zip and move it to root folder
        public static bool GetFilesOnlyInExtractedZip(string SourcePath)
        {
            bool success = false;

            try
            {
                IAPL.Transport.Transactions.ServerDetails SrvrDetails = new IAPL.Transport.Transactions.ServerDetails();

                int FileExist = System.IO.Directory.GetFiles(SourcePath).Length;
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(SourcePath);
                if (FileExist.Equals(0))
                {
                    foreach (System.IO.DirectoryInfo g in dir.GetDirectories())
                    {
                        string FolderInZip = SourcePath + @"\" + g.ToString();
                        foreach (string file in System.IO.Directory.GetFiles(FolderInZip))
                        {
                            string FileInsideFolderInZip = file.ToString();
                            string DestinationFilePath   = SourcePath + @"\" + SrvrDetails.getFileNameOnly(file.ToString());
                            File.Copy(FileInsideFolderInZip, DestinationFilePath);
                            File.Delete(FileInsideFolderInZip);
                        }
                        if (!FolderInZip.Equals(""))
                        {
                            System.IO.Directory.Delete(FolderInZip, true);
                        }
                    }
                }
                success = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(success);
        }
Exemplo n.º 51
0
        private string getLogFilePath()
        {
            this.exePath = Properties.Settings.Default.CNPath.Replace("\\game_patch", "");
            if (this.exePath == null)
            {
                return(null);
            }
            string r3dLogDirectory = this.getR3dLogDirectory(this.exePath);

            Process process = Utilities.GetProcess("League of Legends");

            System.DateTime    startTime = process.StartTime;
            System.IO.FileInfo fileInfo;
            do
            {
                System.Threading.Thread.Sleep(5000);
                System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(r3dLogDirectory);
                fileInfo = (
                    from x in directoryInfo.GetFiles("*.txt")
                    orderby x.LastWriteTime descending
                    select x).ToArray <System.IO.FileInfo>()[0];
            }while (fileInfo.CreationTime < startTime);
            return(fileInfo.FullName);
        }
Exemplo n.º 52
0
        public IActionResult Index(string path = "")
        {
            path = ValidatePath(path);

            path = path.Replace('!', '/');

            var baseDir = new System.IO.DirectoryInfo(path);
            var model   = new RssListViewModel
            {
                CurrentDir  = baseDir,
                Directories = baseDir.EnumerateDirectories()
                              .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden))
                              .Take(100)
                              .OrderBy(x => x.Name),
                Files = baseDir.EnumerateFiles()
                        .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden))
                        .Take(100)
                        .OrderBy(x => x.Name),
            };

            model.DisplayParentLink = path != _baseDir && model.CurrentDir.Parent != null;

            return(View(model));
        }
Exemplo n.º 53
0
 public Form3JavaPathAndOpenJDK()
 {
     InitializeComponent();
     buttonSkip.Hide();
     try
     {
         System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(GetJavaInstallationPath());
         textBoxJAVA_HOME.Text = di.Parent.FullName;
     }
     catch (Exception)
     {
         //On a pas pu chopper le JavaHome dans les variables d'environnement
         if (Directory.Exists(@"C:\Program Files\Java"))
         {
             textBoxJAVA_HOME.Text = @"C:\Program Files\Java";
         }
         else
         {
             Directory.CreateDirectory(@"C:\Program Files\Java");
             label3.Text      = @"Un répertoire Java a été créé à l'emplacement C:\Program Files\Java. Vous pouvez cliquer sur suivant pour installer Zulu dans celui-ci.";
             label3.ForeColor = Color.Blue;
         }
     }
 }
Exemplo n.º 54
0
        private void GetRestoreDaten()
        {
            System.IO.DirectoryInfo ParentDirectory = new System.IO.DirectoryInfo(Frm_Haupt.sRestorePfad);

            string sTempString = "";
            string sFile       = "";
            string sText       = "";

            CmB_DatumBackup.Items.Clear();

            foreach (System.IO.FileInfo f in ParentDirectory.GetFiles())
            {
                sFile = f.Name.Substring(0, 10);

                if (sTempString != sFile)
                {
                    sText = sFile.Substring(8, 2) + "." + sFile.Substring(5, 2) + "." + sFile.Substring(0, 4);

                    CmB_DatumBackup.Items.Add(sText);
                }

                sTempString = sFile;
            }
        }
Exemplo n.º 55
0
        static void ConfigureLog4Net()
        {
            System.IO.DirectoryInfo dir   = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            String      resourcesDir      = dir.FullName + "\\resources";
            String      log4netConfigFile = resourcesDir + "\\log4net.xml";
            ICollection collection        = XmlConfigurator.Configure(new System.IO.FileInfo(log4netConfigFile));

            string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;

            if (Environment.OSVersion.Version.Major >= 6)
            {
                path = Directory.GetParent(path).FullName;
            }
            path = Path.Combine(path, ".bcephal");
            path = Path.Combine(path, "log");

            var fileAppender = LogManager.GetRepository().GetAppenders().First(appender => appender is RollingFileAppender);

            if (fileAppender != null)
            {
                ((RollingFileAppender)fileAppender).File = Path.Combine(path, Path.GetFileName(((RollingFileAppender)fileAppender).File));
                ((RollingFileAppender)fileAppender).ActivateOptions();
            }
        }
Exemplo n.º 56
0
 public static void _service(string TAG, string logtxt)
 {
     try
     {
         var logfolder = AppDomain.CurrentDomain.BaseDirectory + "\\Log\\Service";
         System.IO.DirectoryInfo di   = new System.IO.DirectoryInfo(logfolder);
         FileSystemAccessRule    fsar = new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow);
         DirectorySecurity       ds   = null;
         if (!di.Exists)
         {
             Directory.CreateDirectory(logfolder);
         }
         ds = di.GetAccessControl();
         ds.AddAccessRule(fsar);
         StreamWriter sw = new StreamWriter(logfolder + "\\service" + DateTime.Today.ToString("yyyyMMdd") + ".txt", true);
         sw.WriteLine(string.Format(@"{0} [{1}] {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TAG, logtxt));
         sw.Close();
         logtxt = string.Empty;
     }
     catch (Exception ex)
     {
         ex.ToString();
     }
 }
Exemplo n.º 57
0
        public ApiVersionInfo GetLastVersion()
        {
            var dictory = new System.IO.DirectoryInfo(basepath + "\\" + filefolder);

            if (!dictory.Exists)
            {
                dictory.Create();
            }
            var file = dictory.GetFiles()
                       .Where(p => p.Name.Contains("swagger"))
                       .OrderByDescending(p => p.LastWriteTime)
                       .FirstOrDefault();

            if (file == null)
            {
                return(null);
            }
            else
            {
                var txt = File.ReadAllText(file.FullName);
                var api = JsonConvert.DeserializeObject <ApiVersionInfo>(txt);
                return(api);
            }
        }
Exemplo n.º 58
0
        private static Dictionary <String, Texture2D> LoadIconDictionary(String IconFolderName)
        {
            Dictionary <String, Texture2D> dictReturn = new Dictionary <string, Texture2D>();
            Texture2D texLoading;

            //Where are the Icons
            String strIconPath = string.Format("{0}/{1}", PathPlugin, IconFolderName);

            //String strIconDBPath = string.Format("{0}/{1}", DBPathPlugin, IconFolderName);

            if (Directory.Exists(strIconPath))
            {
                //get all the png and tga's
                FileInfo[] fileIconsPNG = new System.IO.DirectoryInfo(strIconPath).GetFiles("*.png");
                FileInfo[] fileIconsTGA = new System.IO.DirectoryInfo(strIconPath).GetFiles("*.tga");
                FileInfo[] fileIcons    = fileIconsPNG.Concat(fileIconsTGA).ToArray();

                foreach (FileInfo fileIcon in fileIcons)
                {
                    try
                    {
                        //load the file from the GameDB
                        texLoading = new Texture2D(32, 16, TextureFormat.ARGB32, false);
                        if (LoadImageFromFile(ref texLoading, fileIcon.Name, strIconPath))
                        {
                            dictReturn.Add(fileIcon.Name.ToLower().Replace(".png", "").Replace(".tga", ""), texLoading);
                        }
                    }
                    catch (Exception)
                    {
                        MonoBehaviourExtended.LogFormatted("Unable to load Texture from GameDB:{0}", strIconPath);
                    }
                }
            }
            return(dictReturn);
        }
Exemplo n.º 59
0
        protected override System.IO.FileInfo SaveAsHtml(System.IO.DirectoryInfo dir)
        {
            Excel.Application application = this.workbook.Application;
            FileInfo          xlsX        = new FileInfo(workbook.FullName);
            FileInfo          HTMLFile    = new FileInfo(dir.FullName + Separator + this.FilePath.Name.Replace(xlsX.Extension, HtmlExtension));
            object            fileName    = HTMLFile.FullName;

            dir.Create();
            if (HTMLFile.Exists)
            {
                HTMLFile.Delete();
            }
            workbook.WebOptions.AllowPNG         = true;
            workbook.WebOptions.Encoding         = Office.MsoEncoding.msoEncodingISO88591Latin1;
            workbook.WebOptions.OrganizeInFolder = true;
            workbook.WebOptions.RelyOnCSS        = true;
            workbook.WebOptions.RelyOnVML        = false;
            workbook.WebOptions.TargetBrowser    = Office.MsoTargetBrowser.msoTargetBrowserV3;
            workbook.WebOptions.UseLongFileNames = true;
            workbook.SaveAs(fileName, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
            workbook.Close(objtrue, missing, missing);
            workbook = (Excel.Workbook)application.Workbooks.Open(xlsX.FullName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            return(HTMLFile);
        }
Exemplo n.º 60
0
        private string HandleSaveFileBrowser(string initpath)
        {
            string filetosave = string.Empty;

            saveFileDialog1.ValidateNames   = false;
            saveFileDialog1.CheckFileExists = false;
            saveFileDialog1.CheckPathExists = false;
            saveFileDialog1.Filter          = FileFilter;

            try
            {
                //Set the directory that was in the txt box already if necessary
                System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(initpath);
                if (initpath != String.Empty && dirinfo.Exists)
                {
                    saveFileDialog1.InitialDirectory = initpath;
                }
            }
            catch (Exception)
            { }

            try
            {
                DialogResult result = saveFileDialog1.ShowDialog(this);
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    filetosave = saveFileDialog1.FileName;
                }
                saveFileDialog1.Reset();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(filetosave);
        }