• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IO.FileInfo类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.FileInfo的典型用法代码示例。如果您正苦于以下问题:C# FileInfo类的具体用法?C# FileInfo怎么用?C# FileInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



FileInfo类属于System.IO命名空间,在下文中一共展示了FileInfo类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ExportChart

    private void ExportChart(string fileName, ISymbolicDataAnalysisSolution solution, string formula) {
      FileInfo newFile = new FileInfo(fileName);
      if (newFile.Exists) {
        newFile.Delete();
        newFile = new FileInfo(fileName);
      }
      var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

      using (ExcelPackage package = new ExcelPackage(newFile)) {
        ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model");
        FormatModelSheet(modelWorksheet, solution, formulaParts);

        ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset");
        WriteDatasetToExcel(datasetWorksheet, solution.ProblemData);

        ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs");
        WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset);

        if (solution is IRegressionSolution) {
          ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values");
          WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution);

          ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts");
          AddCharts(chartsWorksheet);
        }
        package.Workbook.Properties.Title = "Excel Export";
        package.Workbook.Properties.Author = "HEAL";
        package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab";

        package.Save();
      }
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:32,代码来源:SymbolicSolutionExcelExporter.cs


示例2: ExecuteScript

 private void ExecuteScript(FileInfo code)
 {
     this.progressLabel.Text = "Evaluating: " + code.Name;
     Application.DoEvents();
     this.Client.CodeManager.Execute<Object>(code, Make.Dictionary<Object>(host => this.Client));
     this.progressBar.Increment(1);
 }
开发者ID:urasandesu,项目名称:metatweet,代码行数:7,代码来源:SplashForm.cs


示例3: CreateTestAndCoverageProcessStartInfo

        public static ProcessStartInfo CreateTestAndCoverageProcessStartInfo(Settings settings, string[] fileNames)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.FileName = @"""" + settings.PartCoverPath + @"""";

            startInfo.Arguments += " --target ";
            startInfo.Arguments += @"""" + settings.MSTestPath + @"""";
            startInfo.Arguments += " --target-work-dir ";
            startInfo.Arguments += @"""" + settings.OutputPath + @"""";    // trim trailing slash?
            startInfo.Arguments += " --target-args ";

            startInfo.Arguments += @"""";
            foreach (string fileName in fileNames)
            {
                FileInfo f = new FileInfo(fileName);
                startInfo.Arguments += " /testcontainer:";
                startInfo.Arguments += f.Name;
            }
            startInfo.Arguments += " /noisolation";
            startInfo.Arguments += " /nologo";
            startInfo.Arguments += " /resultsfile:";
            startInfo.Arguments += settings.TestLogFileName;
            startInfo.Arguments += @"""";

            startInfo.Arguments += " --include " + settings.CoverageReportingAssembliesRegEx;
            startInfo.Arguments += " --output " + @"""" + Path.Combine(settings.OutputPath, settings.CoverageLogFileName) + @"""";

            return startInfo;
        }
开发者ID:StefanN,项目名称:DojoTimer-for-.Net,代码行数:31,代码来源:ProcessStartInfoFactory.cs


示例4: TestWriteStructures

        public void TestWriteStructures(string file)
        {
            var structureReader = new StructureParsingManager();
            var fileInfo = new FileInfo(file);
            IStructureWorkspace structureWorkspace;
            using (var readable = new FileReadableDataLocation(fileInfo))
            {
                structureWorkspace = structureReader.ParseStructures(readable);
            }

            ISdmxObjects structureBeans = structureWorkspace.GetStructureObjects(false);

            string output = string.Format(CultureInfo.InvariantCulture, "test-sdmxv2.1-{0}", fileInfo.Name);
            var writtingManager = new StructureWriterManager();
            using (var outputStream = new FileStream(output, FileMode.Create))
            {
                writtingManager.WriteStructures(structureBeans, new SdmxStructureFormat(StructureOutputFormat.GetFromEnum(StructureOutputFormatEnumType.SdmxV21StructureDocument)), outputStream);
            }

            using (var readable = new FileReadableDataLocation(output))
            {
                XMLParser.ValidateXml(readable, SdmxSchemaEnumType.VersionTwoPointOne);
                var structures = structureReader.ParseStructures(readable);
                Assert.NotNull(structures);
            }
        }
开发者ID:SDMXISTATFRAMEWORK,项目名称:ISTAT_ENHANCED_SDMXRI_WS,代码行数:26,代码来源:TestSdmxV20ToV21.cs


示例5: LoadPlugins

		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();
		}
开发者ID:rudzu,项目名称:Hearthstone-Deck-Tracker,代码行数:29,代码来源:PluginManager.cs


示例6: Execute

		/// <summary>
		/// The process for backing up a directory index is simple:
		/// a) create hard links to all the files in the lucene directory in a temp director
		///	   that gives us the current snapshot, and protect us from lucene's
		///    deleting files.
		/// b) copy the hard links to the destination directory
		/// c) delete the temp directory
		/// </summary>
		public void Execute()
		{
			foreach (var file in Directory.EnumerateFiles(tempPath))
			{
				Notify("Copying " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
				var fullName = new FileInfo(file).FullName;
				FileCopy(file, Path.Combine(destination, Path.GetFileName(file)), fileToSize[fullName]);
				Notify("Copied " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
			}

			try
			{
				IOExtensions.DeleteDirectory(tempPath);
			}
			catch (Exception e) //cannot delete, probably because there is a file being written there
			{
				logger.WarnException(
					string.Format("Could not delete {0}, will delete those on startup", tempPath),
					e);

				foreach (var file in Directory.EnumerateFiles(tempPath))
				{
					MoveFileEx(file, null, MoveFileDelayUntilReboot);
				}
				MoveFileEx(tempPath, null, MoveFileDelayUntilReboot);
			}
		}
开发者ID:JPT123,项目名称:ravendb,代码行数:35,代码来源:DirectoryBackup.cs


示例7: Execute

        public void Execute()
        {
            var files = Directory.GetFiles(SourceFolder, "*.jpg");
            foreach (var file in files)
            {
                try
                {
                    DateTime dt;
                    using (var em = new ExifManager(file))
                    {
                        dt = em.DateTimeOriginal;
                    }

                    if (dt == DateTime.MinValue) continue;

                    var fi = new FileInfo(file);
                    var newName = Path.Combine(DestinantionFolder,
                                               string.Format("{0}.jpg", dt.ToString("yyyy-MM-dd_HH.mm.ss")));
                    fi.MoveTo(newName);
                }
                catch
                {
                }
            }

        }
开发者ID:shinetechchina-tj,项目名称:WinSir.Tools.Photos,代码行数:26,代码来源:RenamedByExif.cs


示例8: ExtractRarArchive

        private static bool ExtractRarArchive(string archive, string destination, FileInfo archiveFI, Rar rar)
        {

            Debugger.LogMessageToFile("[Archive extractor] Found RAR archive: " + archiveFI.FullName);

            #region Open
            if (!rar.Open(archive))
            {
                Debugger.LogMessageToFile("[Archive extractor] Failed to open archive: " + rar.LastErrorText);
                //MessageBox.Show("Failed to open archive " + rar.LastErrorText);
                return false;
            }
            Debugger.LogMessageToFile("[Archive extractor] Archive opened succesfully.");
            #endregion

            #region Extract
            //TODO: Check if destination directory exists and if not, create it
            if (!rar.Unrar(destination))
            {
                Debugger.LogMessageToFile("[Archive extractor] Failed to extract archive: " + rar.LastErrorText);
                //MessageBox.Show("Failed to extract archive " + rar.LastErrorText);
                return false;
            }
            Debugger.LogMessageToFile("[Archive extractor] Archive was extracted succesfully.");
            #endregion

            rar.Close();

            DeleteLeftOfMultiparts(rar);

            return true;

        }
开发者ID:stavrossk,项目名称:MeediFier_for_MeediOS,代码行数:33,代码来源:ArchiveExtractor.cs


示例9: ExtractArchive

        internal static bool ExtractArchive(string archive, string destination)
        {

            //REFACTOR: Only create RAR and ZIP classes after discovering that the file actually has a .zip or .rar extension
            FileInfo archiveFI = new FileInfo(archive);
            Rar rar = new Rar();
            FastZip fz = new FastZip();

            double archivesize = archiveFI.Length * 2;
            char driveLetter = archiveFI.FullName[0];


            if (!CheckDiskSpaceQuota(archivesize, driveLetter)) return false;


            if (archiveFI.Extension == ".rar" || archiveFI.Extension == ".RAR")
                return ExtractRarArchive(archive, destination, archiveFI, rar);

            // ReSharper disable ConvertIfStatementToReturnStatement
            if (archiveFI.Extension == ".zip" || archiveFI.Extension == ".ZIP")
            // ReSharper restore ConvertIfStatementToReturnStatement
                return ExtractZipArchive(archive, destination, fz);

            //TODO: Should this return false?
            return true;

        }
开发者ID:stavrossk,项目名称:MeediFier_for_MeediOS,代码行数:27,代码来源:ArchiveExtractor.cs


示例10: test000_FirstPack

        public void test000_FirstPack()
        {
            FileInfo packFile = getPack("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
            Stream @is = packFile.Open(System.IO.FileMode.Open, FileAccess.Read);
            try
            {
                FileInfo tmppack = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1"));
                FileInfo idxFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.idx"));
                FileInfo tmpPackFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.pack"));

                tmppack.Create().Close();
                idxFile.Create().Close();
                tmpPackFile.Create().Close();

                IndexPack pack = new IndexPack(db, @is, tmppack);
                pack.index(new TextProgressMonitor());
                PackFile file = new PackFile(idxFile, tmpPackFile);

                Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799")));
            }
            finally
            {
                @is.Close();
            }
        }
开发者ID:gilran,项目名称:GitSharp,代码行数:32,代码来源:IndexPackTests.cs


示例11: SortLogs

        public static void SortLogs(string[] logs)
        {
            foreach (var logfile in logs)
            {
                FileInfo info = new FileInfo(logfile);

                if (info.Length <= 1024)
                {
                    try
                    {
                        string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar
                 + "SMALL" + Path.DirectorySeparatorChar;

                        if (!Directory.Exists(destdir))
                            Directory.CreateDirectory(destdir);

                        File.Move(logfile, destdir + Path.GetFileName(logfile));
                        File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog"));
                    }
                    catch { }
                    continue;
                }

                MAVLinkInterface mine = new MAVLinkInterface();

                try
                {
                    using (mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read)))
                    {
                        mine.logreadmode = true;

                        byte[] hbpacket = mine.getHeartBeat();

                        if (hbpacket.Length == 0)
                            continue;

                        MAVLink.mavlink_heartbeat_t hb = (MAVLink.mavlink_heartbeat_t)mine.DebugPacket(hbpacket);

                        mine.logreadmode = false;
                        mine.logplaybackfile.Close();

                        string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar
                            + mine.MAV.aptype.ToString() + Path.DirectorySeparatorChar
                            + hbpacket[3] + Path.DirectorySeparatorChar;

                        if (!Directory.Exists(destdir))
                            Directory.CreateDirectory(destdir);

                        File.Move(logfile, destdir + Path.GetFileName(logfile));

                        try
                        {
                            File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog"));
                        }
                        catch { }
                    }
                }
                catch { continue; }
            }
        }
开发者ID:jdellinger,项目名称:MissionPlanner,代码行数:60,代码来源:LogSort.cs


示例12: Load

		public void Load(FileInfo file)
		{
			using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
			{
				Load(stream);
			}
		}
开发者ID:Corniel,项目名称:AIGames.FourInARow.TheDaltons,代码行数:7,代码来源:GameAnalyser.cs


示例13: CheckForDatabase

        /// <summary>
        /// Writes the database to the location defined in the configuration file if it doesn't exist.
        /// </summary>
        public static void CheckForDatabase()
        {
            // A LocalSqlServer connection string get's added by default. Don't look at that one.
            foreach (ConnectionStringSettings connection in ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>().Where(c => c.Name != "LocalSqlServer"))
            {
                try
                {
                    EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(connection.ConnectionString);
                    SqlCeConnectionStringBuilder sqlCEBuilder = new SqlCeConnectionStringBuilder(builder.ProviderConnectionString);

                    if (!File.Exists(sqlCEBuilder.DataSource))
                    {
                        FileInfo info = new FileInfo(sqlCEBuilder.DataSource);

                        if (!Directory.Exists(info.Directory.FullName))
                        {
                            Directory.CreateDirectory(info.Directory.FullName);
                        }

                        File.WriteAllBytes(info.FullName, EncounterTracker.Properties.Resources.EncounterTracker);
                    }

                    break;
                }
                catch
                {
                }
            }
        }
开发者ID:Brian-Wuest,项目名称:EncounterTracker,代码行数:32,代码来源:WindowServices.cs


示例14: ExploreFolderWithMasks

        /// <summary>
        /// Explores the content of the folder using the given set of file masks.
        /// </summary>
        /// <param name="path">The root folder to explore.</param>
        /// <param name="masks">A collection of file masks to match against.</param>
        private void ExploreFolderWithMasks(String path, String[] masks)
        {
            this.knownPathes.Add(path);

            //checks the directory for each mask provided
            foreach (String mask in masks)
            {
                String[] files = Directory.GetFiles(path, mask);
                foreach (String file in files)
                {
                    //prevents the addition of the same file multiple times if it happens to match multiple masks
                    if (!this.foundFiles.Contains(file))
                    {
                        this.foundFiles.Add(file);
                    }
                }
            }
            if (!recursive) return;
            String[] dirs = Directory.GetDirectories(path);
            foreach (String dir in dirs)
            {
                try
                {
                    if (!this.knownPathes.Contains(dir))
                    {
                        FileInfo info = new FileInfo(dir);
                        if ((info.Attributes & FileAttributes.Hidden) == 0)
                            this.ExploreFolderWithMasks(dir, masks);
                    }
                }
                catch { /* Might be system folder.. */ };
            }
        }
开发者ID:heon21st,项目名称:flashdevelop,代码行数:38,代码来源:PathWalker.cs


示例15: WebViewer

		public WebViewer(FileInfo file)
		{
			InitializeComponent();
			File = file;
			Text = Path.GetFileNameWithoutExtension(File.FullName);

			_childBrowser = new WebControl();
			_childBrowser.WebView = new WebView();
			_childBrowser.WebView.FileDialog += OnProcessFileDialog;
			_childBrowser.WebView.BeforeDownload += OnWebViewBeforeDownload;
			_childBrowser.WebView.DownloadUpdated += OnWebViewDownloadUpdated;
			_childBrowser.WebView.DownloadCompleted += OnWebViewDownloadCompleted;
			_childBrowser.WebView.DownloadCanceled += OnWebViewDownloadCanceled;
			_childBrowser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36";
			Controls.Add(_childBrowser);

			_browser = new WebControl();
			_browser.WebView = new WebView();
			_browser.Dock = DockStyle.Fill;
			_browser.WebView.LoadCompleted += OnMainWebViewLoadComplete;
			_browser.WebView.NewWindow += OnMainWebViewNewWindow;
			_browser.WebView.BeforeDownload += OnWebViewBeforeDownload;
			_browser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36";
			Controls.Add(_browser);

			_browser.BringToFront();
		}
开发者ID:w01f,项目名称:VolgaTeam.Dashboard,代码行数:27,代码来源:WebViewer.cs


示例16: LoadAll

        internal static IList<Test> LoadAll()
        {
            var file = new FileInfo("tests.xml");

            if (!file.Exists)
                return new Test[0];

            XmlDocument xml = new XmlDocument();
            using (var fs = file.OpenRead())
                xml.Load(fs);

            var ret = new List<Test>();
            foreach (XmlNode node in xml.SelectNodes("/Tests/*"))
            {
                var n = node.SelectSingleNode("./Type");

                if (n == null)
                    throw new InvalidOperationException("Test Type must be informed.");

                var typeName = n.InnerText;
                var type = FindType(typeName);

                if (type == null)
                    throw new InvalidOperationException(string.Format("'{0}' is not a valid Test.", typeName));

                var obj = (Test)Activator.CreateInstance(type);
                node.ToEntity(obj);

                ret.Add(obj);
            }

            return ret;
        }
开发者ID:hcesar,项目名称:Chess,代码行数:33,代码来源:Test.cs


示例17: Export

        /// <summary>
        /// Экспортирует массив данных в XLSX формат с учетом выбранной локали
        /// </summary>
        /// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
        /// <param name="localisation">Локализация</param>
        /// <returns>Успешное завершение операции</returns>
        public override bool Export(String path, Localisation localisation)
        {
            try
            {
                if (!path.EndsWith(".xlsx"))
                    path += ".xlsx";

                log.Info(String.Format("Export to .xlsx file to: {0}", path));
                var timer = new Stopwatch();
                timer.Start();
                var file = new FileInfo(path);
                using (var pck = new ExcelPackage(file))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
                    ws.Cells["A1"].LoadFromDataTable(dataTable, true);
                    ws.Cells.AutoFitColumns();
                    pck.Save();
                }

                timer.Stop();
                log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Can't export to .xlsx file!", ex);
                return false;
            }
        }
开发者ID:nozdrenkov,项目名称:CSVConverter,代码行数:35,代码来源:XLSXConverter.cs


示例18: DecryptFile

        public DecryptFile(FileInfo decryptedFile, FileInfo encryptedFile)
            : this()
        {
            if (decryptedFile != null)
            {
                ID = System.IO.Path.GetFileNameWithoutExtension(decryptedFile.Name);
                Name = decryptedFile.Name;
                Path = decryptedFile.DirectoryName;
                FileDateTime = decryptedFile.LastWriteTime.ToString();
                Exists = decryptedFile.Exists;
            }
            else
            {
                Exists = false;
            }

            if (encryptedFile != null)
            {
                if (ID == null)
                {
                    ID = System.IO.Path.GetFileNameWithoutExtension(encryptedFile.Name);
                }
                EncryptName = encryptedFile.Name;
                EncryptPath = encryptedFile.DirectoryName;
                EncryptDateTime = encryptedFile.LastWriteTime.ToString();
                EncryptExists = encryptedFile.Exists;
            }
            else
            {
                EncryptExists = false;
            }
        }
开发者ID:JamesWhiteAtx,项目名称:Linkout,代码行数:32,代码来源:DecryptFile.cs


示例19: ArchiveException

        /// <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)
            {
            }
        }
开发者ID:RonFields72,项目名称:EmailACHReportsToVendors,代码行数:37,代码来源:FileHelper.cs


示例20: RemoveCustomACLs

        // http://stackoverflow.com/questions/12811850/setting-a-files-acl-to-be-inherited
        private static void RemoveCustomACLs(string destination)
        {
            FileInfo fileInfo;
            FileSecurity fileSecurity;
            AuthorizationRuleCollection fileRules;

            fileInfo = new FileInfo(destination);
            fileSecurity = fileInfo.GetAccessControl();
            fileSecurity.SetAccessRuleProtection(false, false);

            fileSecurity.SetOwner(WindowsIdentity.GetCurrent().User);

            /*
             * Only fetch the explicit rules since I want to keep the inherited ones. Not
             * sure if the target type matters in this case since I am not examining the
             * IdentityReference.
             */
            fileRules = fileSecurity.GetAccessRules(includeExplicit: true,
                                     includeInherited: false, targetType: typeof(NTAccount));
            /*
             * fileRules is a AuthorizationRuleCollection object, which can contain objects
             * other than FileSystemAccessRule (in theory), but GetAccessRules should only
             * ever return a collection of FileSystemAccessRules, so we will just declare
             * rule explicitly as a FileSystemAccessRule.
             */
            foreach (FileSystemAccessRule rule in fileRules)
            {
                /*
                 * Remove any explicit permissions so we are just left with inherited ones.
                 */
                fileSecurity.RemoveAccessRule(rule);
            }

            fileInfo.SetAccessControl(fileSecurity);
        }
开发者ID:niv,项目名称:catflap,代码行数:36,代码来源:Utils.cs



注:本文中的System.IO.FileInfo类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IO.FileNotFoundException类代码示例发布时间:2022-05-26
下一篇:
C# IO.File类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap