C# File.SetAttributes的代码示例

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

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


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

File.SetAttributes的代码示例1 - OpenForWrite()

    using System.IO;

        private static SafeFileHandle OpenForWrite(ITracer tracer, string fileName)
        {
            SafeFileHandle handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero);
            if (handle.IsInvalid)
            {
                // If we get a access denied, try reverting the acls to defaults inherited by parent
                if (Marshal.GetLastWin32Error() == AccessDeniedWin32Error)
                {
                    tracer.RelatedEvent(
                        EventLevel.Warning,
                        "FailedOpenForWrite",
                        new EventMetadata
                        {
                            { TracingConstants.MessageKey.WarningMessage, "Received access denied. Attempting to delete." },
                            { "FileName", fileName }
                        });

                    File.SetAttributes(fileName, FileAttributes.Normal);
                    File.Delete(fileName);

                    handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero);
                }
            }

            return handle;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:NativeMethods.cs

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

File.SetAttributes的代码示例2 - PrefetchBuildsIdxWhenMissingFromPrefetchPack()

    using System.IO;

        [TestCase, Order(2)]
        public void PrefetchBuildsIdxWhenMissingFromPrefetchPack()
        {
            string[] prefetchPacks = this.ReadPrefetchPackFileNames();
            prefetchPacks.Length.ShouldBeAtLeast(1, "There should be at least one prefetch pack");

            string idxPath = Path.ChangeExtension(prefetchPacks[0], ".idx");
            idxPath.ShouldBeAFile(this.fileSystem);
            File.SetAttributes(idxPath, FileAttributes.Normal);
            this.fileSystem.DeleteFile(idxPath);
            idxPath.ShouldNotExistOnDisk(this.fileSystem);

            // Prefetch should rebuild the missing idx
            this.Enlistment.Prefetch("--commits");
            this.PostFetchJobShouldComplete();

            idxPath.ShouldBeAFile(this.fileSystem);

            // All of the original prefetch packs should still be present
            string[] newPrefetchPacks = this.ReadPrefetchPackFileNames();
            newPrefetchPacks.ShouldContain(prefetchPacks, (item, expectedValue) => { return string.Equals(item, expectedValue); });
            this.AllPrefetchPacksShouldHaveIdx(newPrefetchPacks);
            this.TempPackRoot.ShouldBeADirectory(this.fileSystem).WithNoItems();
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:26,代码来源:PrefetchVerbWithoutSharedCacheTests.cs

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

File.SetAttributes的代码示例3 - 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的代码示例类中的SetAttributes的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.SetAttributes的代码示例4 - 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的代码示例类中的SetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.SetAttributes的代码示例5 - CreateSymbolicLink()

    using System.IO;

        public static bool CreateSymbolicLink(string source, string target, bool isDirectory)
        {
            bool success = false;
            try
            {
                // In case the file is marked as readonly
                if (File.Exists(source))
                {
                    File.SetAttributes(source, FileAttributes.Normal);
                    File.Delete(source);
                }
                else if (Directory.Exists(source))
                {
                    Directory.Delete(source);
                }

                int releaseId = int.Parse(GetRegistryLocalMachineSubKeyValue(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "0"));

                int flags = isDirectory ? SYMBOLIC_LINK_FLAG_DIRECTORY : SYMBOLIC_LINK_FLAG_FILE;
                if (releaseId >= 1703) // Verify that the Windows build is equal or above 1703, as SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE was introduced at that version. Using it on older version will cause an error 87 and symlinks won't be created
                    flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;

                success = CreateSymbolicLink(source, target, flags);
            }
            catch { }
            return success;
        }
    

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

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

File.SetAttributes的代码示例6 - 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的代码示例类中的SetAttributes的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.SetAttributes的代码示例7 - CopySiteMapFiles()

    using System.IO;

        /// 
        /// This is used to copy site map files to the help format output folders including those for any child
        /// site map entries.
        /// 
        /// The site entry containing the files to copy
        private void CopySiteMapFiles(TocEntry site)
        {
            if(site.SourceFile.Path.Length != 0)
            {
                // Set the destination filename which will always match the source filename for site map files.
                site.DestinationFile = site.SourceFile.PersistablePath;

                foreach(string baseFolder in this.HelpFormatOutputFolders)
                    if(!File.Exists(baseFolder + site.DestinationFile))
                    {
                        this.ReportProgress("{0} -> {1}{2}", site.SourceFile, baseFolder, site.DestinationFile);

                        // All attributes are turned off so that we can delete it later
                        File.Copy(site.SourceFile, baseFolder + site.DestinationFile, true);
                        File.SetAttributes(baseFolder + site.DestinationFile, FileAttributes.Normal);
                    }
            }

            if(site.Children.Count != 0)
                foreach(TocEntry entry in site.Children)
                    this.CopySiteMapFiles(entry);
        }
    

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

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

File.SetAttributes的代码示例8 - Dispose()

    using System.IO;

        /// 
        /// At disposal, copy the script and style files if any topics with code blocks were encountered
        /// 
        /// Pass true to dispose of the managed and unmanaged resources or false to just
        /// dispose of the unmanaged resources.
        protected override void Dispose(bool disposing)
        {
            string destStylesheet, destScriptFile;

            if(disposing && hasColorizedCodeBlocks)
            {
                foreach(string outputPath in outputPaths)
                {
                    destStylesheet = Path.Combine(outputPath, stylesheetAttrPath.Replace("../", String.Empty));
                    destScriptFile = Path.Combine(outputPath, scriptFileAttrPath.Replace("../", String.Empty));

                    if(Path.DirectorySeparatorChar != '/')
                    {
                        destStylesheet = destStylesheet.Replace('/', Path.DirectorySeparatorChar);
                        destScriptFile = destScriptFile.Replace('/', Path.DirectorySeparatorChar);
                    }

                    if(!Directory.Exists(Path.GetDirectoryName(destStylesheet)))
                        Directory.CreateDirectory(Path.GetDirectoryName(destStylesheet));

                    if(!Directory.Exists(Path.GetDirectoryName(destScriptFile)))
                        Directory.CreateDirectory(Path.GetDirectoryName(destScriptFile));

                    // Don't copy if already there (i.e. overridden by a copy in the project or copied by another
                    // instance).
                    if(!File.Exists(destStylesheet))
                    {
                        File.Copy(stylesheet, destStylesheet);

                        // All attributes are turned off so that we can delete it later
                        File.SetAttributes(destStylesheet, FileAttributes.Normal);
                    }

                    // Raise an event to indicate that a file was created
                    OnComponentEvent(new FileCreatedEventArgs(this.GroupId, "Code Block Component", null,
                        destStylesheet, true));

                    if(!File.Exists(destScriptFile))
                    {
                        File.Copy(scriptFile, destScriptFile);
                        File.SetAttributes(destScriptFile, FileAttributes.Normal);
                    }

                    OnComponentEvent(new FileCreatedEventArgs(this.GroupId, "Code Block Component", null,
                        destScriptFile, true));
                }
            }

            base.Dispose(disposing);
        }
    

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

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

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