C# File.GetAttributes的代码示例

通过代码示例来学习C# File.GetAttributes方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


File.GetAttributes是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.GetAttributes() 已经帮大家高亮显示了,大家可以重点学习File.GetAttributes() 方法的写法,从而快速掌握该方法的应用。

File.GetAttributes的代码示例1 - OnBeforeExpand()

    using System.IO;

        public void OnBeforeExpand()
        {
            if (IsExpanded || !CanExpand) return;
            Nodes.Clear();
            foreach (string str in Directory.GetDirectories($"{_path}\\"))
            {
                if (File.GetAttributes(str).HasFlag(FileAttributes.Directory))
                    Nodes.Add(new ExplorerFolder(str));
            }
            foreach (string str in Directory.GetFiles($"{_path}\\"))
            {
                if (!File.GetAttributes(str).HasFlag(FileAttributes.Directory))
                    Nodes.Add(new ExplorerFile(str));
            }
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:17,代码来源:ExplorerFolder.cs

在OnBeforeExpand()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例2 - CanSaveAsCopyReadOnlyFile()

    using System.IO;

        [Test]
        public void CanSaveAsCopyReadOnlyFile()
        {
            using (var original = new TemporaryFile())
            {
                try
                {
                    using (var copy = new TemporaryFile())
                    {
                        // Arrange
                        using (var wb = new XLWorkbook())
                        {
                            var sheet = wb.Worksheets.Add("TestSheet");
                            wb.SaveAs(original.Path);
                        }
                        File.SetAttributes(original.Path, FileAttributes.ReadOnly);

                        // Act
                        using (var wb = new XLWorkbook(original.Path))
                        {
                            wb.SaveAs(copy.Path);
                        }

                        // Assert
                        Assert.IsTrue(File.Exists(copy.Path));
                        Assert.IsFalse(File.GetAttributes(copy.Path).HasFlag(FileAttributes.ReadOnly));
                    }
                }
                finally
                {
                    // Tear down
                    File.SetAttributes(original.Path, FileAttributes.Normal);
                }
            }
        }
    

开发者ID:ClosedXML,项目名称:ClosedXML,代码行数:37,代码来源:SavingTests.cs

在CanSaveAsCopyReadOnlyFile()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例3 - SetHost()

    using System.IO;

        /// 
        /// 
        /// 
        /// 
        /// 空值表示删除对应的host记录
        /// 测试用
        public static void SetHost(string host, string ip, string hostsPath = null) {
            GetIp(host, out long position, hostsPath);
            if (position == -2) {
                File.WriteAllText(hostsPath, $"{ip} {host}");
                return;
            }
            if (string.IsNullOrEmpty(hostsPath)) {
                hostsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers\\etc\\hosts");
            }
            //通常情况下这个文件是只读的,所以写入之前要取消只读
            File.SetAttributes(hostsPath, File.GetAttributes(hostsPath) & (~FileAttributes.ReadOnly));
            byte[] buffer = new byte[]{ };
            using (MemoryStream ms = new MemoryStream())
            using (StreamWriter sw = new StreamWriter(ms))
            using (FileStream fs = new FileStream(hostsPath, FileMode.OpenOrCreate, FileAccess.Read))
            using (StreamReader sr = new StreamReader(fs)) {
                bool writed = false;
                while (true) {
                    long p = sr.BaseStream.Position;
                    string line = sr.ReadLine();
                    if (p == position) {
                        if (!string.IsNullOrEmpty(ip)) {
                            sw.WriteLine($"{ip} {host}");
                        }
                        writed = true;
                    }
                    else {
                        sw.WriteLine(line);
                    }
                    if (sr.EndOfStream) {
                        break;
                    }
                }
                if (!writed) {
                    sw.WriteLine($"{ip} {host}");
                }
                sw.Flush();
                buffer = ms.ToArray();
            }
            File.WriteAllBytes(hostsPath, buffer);
        }
    

开发者ID:ntminer,项目名称:NtMiner,代码行数:49,代码来源:Hosts.cs

在SetHost()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例4 - ForceCopy()

    using System.IO;

        public static void ForceCopy(string source, string destination, FileCopyDestReadOnlyPolicy destinationReadOnlyPolicy)
        {
            if (File.Exists(destination))
            {
                FileAttributes attributes = File.GetAttributes(destination);
                attributes &= ~FileAttributes.ReadOnly;
                File.SetAttributes(destination, attributes);
            }

            File.Copy(source, destination, true);

            if (destinationReadOnlyPolicy != FileCopyDestReadOnlyPolicy.Preserve)
            {
                FileAttributes attributes = File.GetAttributes(destination);
                if (destinationReadOnlyPolicy == FileCopyDestReadOnlyPolicy.SetReadOnly)
                {
                    attributes |= FileAttributes.ReadOnly;
                }
                else
                {
                    attributes &= ~FileAttributes.ReadOnly;
                }
                File.SetAttributes(destination, attributes);
            }
        }
    

开发者ID:ubisoft,项目名称:Sharpmake,代码行数:27,代码来源:Util.cs

在ForceCopy()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例5 - FilePreparePath()

    using System.IO;
#endif
#if NET45 || NETSTANDARD1_3 || NETSTANDARD1_6
        /// 
        /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter.
        /// 
        /// The requested URL, such as "http://Myserver/Mypath/Myfile.asp".
        /// The XmlTextWriter to which you want to save to.
        public void LoadHtmlAsXml(string htmlUrl, XmlWriter writer)
        {
            HtmlDocument doc = Load(htmlUrl);
            doc.Save(writer);
        }
#endif

        #endregion

        #region Private Methods

        private static void FilePreparePath(string target)
        {
            if (File.Exists(target))
            {
                FileAttributes atts = File.GetAttributes(target);
                File.SetAttributes(target, atts & ~FileAttributes.ReadOnly);
            }
            else
            {
                string dir = Path.GetDirectoryName(target);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
        }
    

开发者ID:zzzprojects,项目名称:html-agility-pack,代码行数:35,代码来源:HtmlWeb.cs

在FilePreparePath()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例6 - RecursiveCopy()

    using System.IO;

        /// 
        /// This copies files from the specified source folder to the specified destination folder.  If any
        /// subfolders are found below the source folder and the wildcard is "*.*", the subfolders are also
        /// copied recursively.
        /// 
        /// The source path from which to copy
        /// The destination path to which to copy
        /// A reference to the file count variable
        private void RecursiveCopy(string sourcePath, string destinationPath, ref int fileCount)
        {
            if(sourcePath == null)
                throw new ArgumentNullException(nameof(sourcePath));

            if(destinationPath == null)
                throw new ArgumentNullException(nameof(destinationPath));

            int idx = sourcePath.LastIndexOf('\\');

            string dirName = sourcePath.Substring(0, idx), fileSpec = sourcePath.Substring(idx + 1), filename;

            foreach(string name in Directory.EnumerateFiles(dirName, fileSpec))
            {
                filename = destinationPath + Path.GetFileName(name);

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

                // All attributes are turned off so that we can delete it later
                File.Copy(name, filename, true);
                File.SetAttributes(filename, FileAttributes.Normal);

                fileCount++;

                if((fileCount % 500) == 0)
                    this.ReportProgress("Copied {0} files", fileCount);
            }

            // For "*.*", copy subfolders too
            if(fileSpec == "*.*")
            {
                // Ignore hidden folders as they may be under source control and are not wanted
                foreach(string folder in Directory.EnumerateDirectories(dirName))
                    if((File.GetAttributes(folder) & FileAttributes.Hidden) != FileAttributes.Hidden)
                        this.RecursiveCopy(folder + @"\*.*", destinationPath + folder.Substring(dirName.Length + 1) + @"\",
                            ref fileCount);
            }
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:49,代码来源:BuildProcess.HelpFileUtils.cs

在RecursiveCopy()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例7 - Execute()

    using System.IO;

        #endregion

        #region Execute method
        //=====================================================================

        /// 
        /// This is used to execute the task and clean the output folder
        /// 
        /// True on success or false on failure.
        public override bool Execute()
        {
            string projectPath;

            try
            {
                projectPath = Path.GetDirectoryName(Path.GetFullPath(this.ProjectFile));

                // Make sure we start out in the project's output folder
                // in case the output folder is relative to it.
                Directory.SetCurrentDirectory(Path.GetDirectoryName(Path.GetFullPath(projectPath)));

                // Clean the working folder
                if(!String.IsNullOrEmpty(this.WorkingPath))
                {
                    if(!Path.IsPathRooted(this.WorkingPath))
                        this.WorkingPath = Path.GetFullPath(Path.Combine(projectPath, this.WorkingPath));

                    if(Directory.Exists(this.WorkingPath))
                    {
                        BuildProcess.VerifySafePath(nameof(WorkingPath), this.WorkingPath, projectPath);
                        Log.LogMessage(MessageImportance.High, "Removing working folder...");
                        Directory.Delete(this.WorkingPath, true);
                    }
                }

                if(!Path.IsPathRooted(this.OutputPath))
                    this.OutputPath = Path.GetFullPath(Path.Combine(projectPath, this.OutputPath));

                if(Directory.Exists(this.OutputPath))
                {
                    Log.LogMessage(MessageImportance.High, "Removing build files...");
                    BuildProcess.VerifySafePath(nameof(OutputPath), this.OutputPath, projectPath);

                    // Read-only and/or hidden files and folders are ignored as they are assumed to be
                    // under source control.
                    foreach(string file in Directory.EnumerateFiles(this.OutputPath))
                        if((File.GetAttributes(file) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                            File.Delete(file);
                        else
                            Log.LogMessage(MessageImportance.High, "Skipping read-only or hidden file '{0}'", file);

                    Log.LogMessage(MessageImportance.High, "Removing build folders...");

                    foreach(string folder in Directory.EnumerateDirectories(this.OutputPath))
                        try
                        {
                            // Some source control providers have a mix of read-only/hidden files within a folder
                            // that isn't read-only/hidden (i.e. Subversion).  In such cases, leave the folder alone.
                            if(Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Any(f =>
                              (File.GetAttributes(f) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) != 0))
                                Log.LogMessage(MessageImportance.High, "Skipping folder '{0}' as it contains read-only or hidden folders/files", folder);
                            else
                                if((File.GetAttributes(folder) & (FileAttributes.ReadOnly | FileAttributes.Hidden)) == 0)
                                    Directory.Delete(folder, true);
                                else
                                    Log.LogMessage(MessageImportance.High, "Skipping folder '{0}' as it is read-only or hidden", folder);
                        }
                        catch(IOException ioEx)
                        {
                            Log.LogMessage(MessageImportance.High, "Did not delete folder '{0}': {1}", folder, ioEx.Message);
                        }
                        catch(UnauthorizedAccessException uaEx)
                        {
                            Log.LogMessage(MessageImportance.High, "Did not delete folder '{0}': {1}", folder, uaEx.Message);
                        }

                    // Delete the log file too if it exists
                    if(!String.IsNullOrEmpty(this.LogFileLocation) && File.Exists(this.LogFileLocation))
                    {
                        Log.LogMessage(MessageImportance.High, "Removing build log...");
                        File.Delete(this.LogFileLocation);
                    }
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                Log.LogError(null, "CT0001", "CT0001", "SHFB", 0, 0, 0, 0,
                    "Unable to clean output folder.  Reason: {0}", ex);
                return false;
            }

            return true;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:96,代码来源:CleanHelp.cs

在Execute()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了3次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.GetAttributes的代码示例8 - CloseProject()

    using System.IO;

        /// 
        /// Close the current project
        /// 
        /// True if the project was closed, false if not
        private bool CloseProject()
        {
            BaseContentEditor content;
            IDockContent[] contents;

            if(projectExplorer.AskToSaveProject())
            {
                miClearOutput_Click(this, EventArgs.Empty);
                this.KillWebServer();

                // Dispose of the preview window as it doesn't make much sense to save its state
                if(previewWindow != null)
                {
                    previewWindow.Dispose();
                    previewWindow = null;
                }

                if(outputWindow != null)
                {
                    outputWindow.ResetLogViewer();
                    outputWindow.LogFile = null;
                }

                if(entityReferencesWindow != null)
                    entityReferencesWindow.CurrentProject = null;

                if(projectExplorer.CurrentProject != null && Settings.Default.PerUserProjectState)
                {
                    // If hidden, unhide it so that DockPanel can write to it.  We'll hide it again afterwards.
                    bool isHidden = (File.Exists(projectExplorer.CurrentProject.Filename + WindowStateSuffix) &&
                      (File.GetAttributes(projectExplorer.CurrentProject.Filename +
                        WindowStateSuffix) & FileAttributes.Hidden) != 0);

                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;

                        if(isHidden)
                            File.SetAttributes(projectExplorer.CurrentProject.Filename + WindowStateSuffix,
                                FileAttributes.Normal);

                        dockPanel.SaveAsXml(projectExplorer.CurrentProject.Filename + WindowStateSuffix);

                        if(isHidden)
                            File.SetAttributes(projectExplorer.CurrentProject.Filename + WindowStateSuffix,
                                FileAttributes.Hidden);
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }

                // Close all content editors
                contents = new IDockContent[dockPanel.Contents.Count];
                dockPanel.Contents.CopyTo(contents, 0);

                foreach(IDockContent dockContent in contents)
                {
                    content = dockContent as BaseContentEditor;

                    // If one can't close, don't close the project
                    if(content != null && !content.CanClose)
                    {
                        projectExplorer.Activate();
                        return false;
                    }

                    if(dockContent.DockHandler.HideOnClose)
                        dockContent.DockHandler.Hide();
                    else
                        dockContent.DockHandler.Close();
                }

                if(project != null)
                {
                    ComponentCache.Clear();
                    project.Dispose();
                }

                project = projectExplorer.CurrentProject = projectProperties.CurrentProject = null;
                this.UpdateFilenameInfo();

                miDocumentation.Visible = miCloseProject.Enabled = miClose.Enabled = miCloseAll.Enabled =
                    miCloseAllButCurrent.Enabled = miSave.Enabled = miSaveAs.Enabled = miSaveAll.Enabled =
                    tsbSave.Enabled = tsbSaveAll.Enabled = miProjectExplorer.Visible =
                    miExplorerSeparator.Visible = tsbBuildProject.Enabled = tsbViewHelpFile.Enabled =
                    miPreviewTopic.Enabled = tsbPreviewTopic.Enabled = false;

                return true;
            }

            return false;
        }
    

开发者ID:EWSoftware,项目名称:SHFB,代码行数:100,代码来源:MainForm.cs

在CloseProject()方法中,File的代码示例类中的GetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

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