Inheritance: FileSystemInfo
Example #1
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);
        }
 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;
 }
		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();
		}
Example #4
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);
        }
        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;
             * */
        }
        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);
            }
        }
        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
        }
        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;
        }
Example #9
1
 private static void CreateDirectoryIfNotExists(DirectoryInfo directoryInfo)
 {
     if(!directoryInfo.Exists) {
         CreateDirectoryIfNotExists(directoryInfo.Parent);
         directoryInfo.Create();
     }
 }
Example #10
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;
        }
Example #11
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);
        }
Example #12
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;
                }
            }
        }
Example #13
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);
                }
            }
        }
        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;
        }
        /// <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.
                    }
                }
            }
        }
        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);
        }
Example #17
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;
                    }
                }
            }
        }
        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);
            }
        }
Example #19
1
        public static void Copy(string sourceDirectory, string targetDirectory)
        {
            DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
            DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

            CopyAll(diSource, diTarget);
        }
		/// <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;
		}
Example #21
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);
        }
Example #22
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;
        }
Example #23
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();
            }
        }
Example #24
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());
            }
        }
Example #25
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;
        }
        /// <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)
            {
            }
        }
Example #27
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();
            }
        }
        /// <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
            }
        }
Example #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;

                        }

                    }
                }

            }
        }
        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();
        }