当前位置: 首页>>代码示例>>C#>>正文


C# FileInfo.OpenRead方法代码示例

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


在下文中一共展示了FileInfo.OpenRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: 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

示例2: FileResponse

 public FileResponse(string path, IHttpRequest request)
     : base()
 {
     file = new FileInfo(path);
     var time = file.LastWriteTime.ToUniversalTime().ToString("r");
     this.Headers[eHttpHeader.ContentType] = MIME.GetContengTypeByExtension(System.IO.Path.GetExtension(path));
     if (time == request.Headers[eHttpHeader.IfModifiedSince])
     {
         this.Write304();
     }
     else
     {
         Headers.Add("Last-Modified", file.LastWriteTime.ToUniversalTime().ToString("r"));
         if (request.Headers[eHttpHeader.AcceptEncoding].Contains("gzip"))
         {
             using (var compress = new GZipStream(content, CompressionMode.Compress,true))
             {
                 compress.Write(file.OpenRead().ReadAll());
             }
             Headers.Add(eHttpHeader.ContentEncoding, "gzip");
         }
         else
         {
              file.OpenRead().CopyTo(content);
         }
     }
 }
开发者ID:sdzxwxlsj,项目名称:lsjutil,代码行数:27,代码来源:FileResponse.cs

示例3: DigestFile

        public static String DigestFile(String uri, DigestMode mode = DigestMode.SHA1)
        {
            byte[] data = new byte[0];

            if (File.Exists(uri))
            {
                FileInfo fi = new FileInfo(uri);
                switch (mode)
                {
                    case DigestMode.MD5:
                        data =    MD5.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA1:
                        data =   SHA1.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA256:
                        data = SHA256.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA384:
                        data = SHA384.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA512:
                        data = SHA512.Create().ComputeHash(fi.OpenRead());
                        break;
                }
            }

            return Engine.Byte2hex(data);
        }
开发者ID:dearing,项目名称:sandbox,代码行数:29,代码来源:hash.cs

示例4: Main

        static void Main(string[] args)
        {
            var inputFile = new FileInfo("input.txt");
            var outputFile = new FileInfo("output.txt");
            var decryptedFile = new FileInfo("decrypted.txt");

            // delete files if they already exists
            if (inputFile.Exists) inputFile.Delete();
            if (outputFile.Exists) outputFile.Delete();
            if (decryptedFile.Exists) decryptedFile.Delete();

            // write test data to input file
            using (var writer = new StreamWriter(inputFile.Create()))
                writer.WriteLine("Some plain text which is not already encrypted");

            // initialise des algorithm
            var desProvider = new DESCryptoServiceProvider();

            // get des generated key and initialization vector
            var key = desProvider.Key;
            var initialisationVector = desProvider.IV;
            Console.WriteLine("Key: {0}\n", Convert.ToBase64String(key));

            Console.WriteLine("Begin encryption ...");
            // encrypt data from input file to output file
            using (var inputStream = inputFile.OpenRead())
            using (var encryptor = desProvider.CreateEncryptor(key, initialisationVector))
            using (var cryptostream = new CryptoStream(outputFile.Create(), encryptor, CryptoStreamMode.Write))
            {
                var bytes = new byte[inputStream.Length - 1];
                inputStream.Read(bytes, 0, bytes.Length);
                Console.WriteLine("Data in input file before encryption: {0}", Encoding.UTF8.GetString(bytes));
                cryptostream.Write(bytes, 0, bytes.Length);
            }

            Console.WriteLine("Encryption finished!");

            // print encryption result
            using (var reader = new StreamReader(outputFile.OpenRead()))
                Console.WriteLine("Encryption result: {0}\n\n", reader.ReadToEnd());

            Console.WriteLine("Begin decryption ...");
            // decrypt data from output file to result file
            using (var outputStream = new StreamWriter(decryptedFile.Create()))
            using (var decryptor = desProvider.CreateDecryptor())
            using (var cryptostream = new StreamReader(new CryptoStream(
                    outputFile.OpenRead(), decryptor, CryptoStreamMode.Read)))
                outputStream.Write(cryptostream.ReadToEnd());

            Console.WriteLine("Decryption finished!");

            // print decryption result
            using (var reader = new StreamReader(decryptedFile.OpenRead()))
                Console.WriteLine("Decryption result: {0}", reader.ReadToEnd());
        }
开发者ID:pashchuk,项目名称:data-security-labs,代码行数:55,代码来源:Program.cs

示例5: OpenFileRead

 private Stream OpenFileRead(FileInfo fileInfo)
 {
     try
     {
         return fileInfo.OpenRead();
     }
     catch (IOException)
     {
         return fileInfo.OpenRead();
     }
 }
开发者ID:rizwan3d,项目名称:elalang,代码行数:11,代码来源:OutputInputService.cs

示例6: getBytesFromFile

        /// <summary>
        /// Obtiene un arreglo de BYTES que representan el contenido binario de un archivo para enviarlo directamente a una BD o hacer algun trabajo con él.
        /// </summary>
        /// <param name="f">FileInfo f del archivo del cual se quiere obtener el arreglo de bytes</param>
        /// <returns>arreglo de bytes para hacer algun trabajo con el.</returns>
        public static byte[] getBytesFromFile(FileInfo f)
        {
            byte[] buffer = null;

            try
            {
                buffer = new byte[f.OpenRead().Length];
                f.OpenRead().Read(buffer, 0, (int)f.OpenRead().Length);
            }
            catch (Exception ex)
            {
                buffer = null;
            }
            return buffer;
        }
开发者ID:royriojas,项目名称:RGEN2,代码行数:20,代码来源:utilidades.cs

示例7: CopyFile

        /// <summary>
        /// Copy the specified file.
        /// </summary>
        ///
        /// <param name="source">The file to copy.</param>
        /// <param name="target">The target of the copy.</param>
        public static void CopyFile(FileInfo source, FileInfo target)
        {
            try
            {
                var buffer = new byte[BufferSize];

                // open the files before the copy
                FileStream
                    ins0 = source.OpenRead();
                target.Delete();
                FileStream xout = target.OpenWrite();

                // perform the copy
                int packetSize = 0;

                while (packetSize != -1)
                {
                    packetSize = ins0.Read(buffer, 0, buffer.Length);
                    if (packetSize != -1)
                    {
                        xout.Write(buffer, 0, packetSize);
                    }
                }

                // close the files after the copy
                ins0.Close();
                xout.Close();
            }
            catch (IOException e)
            {
                throw new EncogError(e);
            }
        }
开发者ID:CreativelyMe,项目名称:encog-dotnet-core,代码行数:39,代码来源:Directory.cs

示例8: NSData

 /// <summary>
 /// Creates a NSData object from a file. Using the files contents as the contents of this NSData object.
 /// </summary>
 /// <param name="file">The file containing the data.</param>
 /// <exception cref="FileNotFoundException">If the file could not be found.</exception>
 /// <exception cref="IOException">If the file could not be read.</exception>
 public NSData(FileInfo file)
 {
     bytes = new byte[(int)file.Length];
     FileStream raf = file.OpenRead();
     raf.Read(bytes, 0, (int)file.Length);
     raf.Close();
 }
开发者ID:swiftpixil,项目名称:plist-cil,代码行数:13,代码来源:NSData.cs

示例9: Compress

        /// <summary>
        /// Compresses the file with the GZip algorithm
        /// </summary>
        /// <param name="sourcePath">Path to the file which will be compressed</param>
        /// <param name="destinationPath">Path to the directory where the compressed file will be copied to</param>
        public static void Compress(string sourcePath, string destinationPath)
        {
            try
            {
                FileInfo fileToCompress = new FileInfo(sourcePath);

                using (FileStream originalFileStream = fileToCompress.OpenRead())
                {
                    if ((File.GetAttributes(fileToCompress.FullName) &
                        FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                    {
                        using (FileStream compressedFileStream = File.Create(destinationPath + "\\" + fileToCompress.Name + ".gz"))
                        {
                            using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                                CompressionMode.Compress))
                            {
                                originalFileStream.CopyTo(compressionStream);

                            }
                        }

                        FileInfo info = new FileInfo(destinationPath + "\\" + fileToCompress.Name + ".gz");
                    }
                }
            }
            catch
            {
            }
        }
开发者ID:DesselBane,项目名称:DarkSeng,代码行数:34,代码来源:GZip.cs

示例10: GetStaticFile

 /// <summary>
 /// 静态页提供示例,未做任何缓存和304响应处理,仅演示用。
 /// </summary>
 public Task GetStaticFile(IOwinContext context)
 {
     if (context.Request.Method == "GET" && context.Request.Path.HasValue)
     {
         string path = HttpHelper.GetMapPath(context.Request.Path.Value);
         FileInfo fi = new FileInfo(path);
         var response = context.Response;
         if (fi.Exists)
         {
             response.ContentType = MimeTypes.GetMimeType(fi.Extension);
             response.ContentLength = fi.Length;
             response.StatusCode = 200;
             using (FileStream fs = fi.OpenRead())
             {
                 fs.CopyTo(response.Body);
             }
         }
         else
         {
             response.StatusCode = 404;
             response.Write("<h1 style='color:red'>很抱歉,出现了404错误。</h1>");
         }
         return HttpHelper.completeTask;
     }
     else
     {
         return HttpHelper.cancelTask;
     }
 }
开发者ID:avatasia,项目名称:OwinFramework,代码行数:32,代码来源:Demo.cs

示例11: DeployTest

        public void DeployTest()
        {
            FileInfo parFile = new FileInfo("ExamplePar/helloworld1.par");
            FileStream fstream = parFile.OpenRead();
            byte[] b = new byte[parFile.Length];
            fstream.Read(b, 0, (int)parFile.Length);
            processDefinitionService.DeployProcessArchive(b);

            IProcessDefinition pd = processDefinitionService.GetProcessDefinition("Hello world 1");
            Assert.IsNotNull(pd);
            //1:first activity state 2:start 3:end
            //Assert.AreEqual(3, pd.Nodes.Count);
            //也要能取出state
            //pd.GetStates("first activity state")

            //要能取出Trnsitions
            //transitions = pd.from("first activity state");
            //transitions = pd.to("end");

            //要能取得Delegations

            /*select * from [dbo].[NBPM_DELEGATION];
              select * from [dbo].[NBPM_NODE];
              select * from [dbo].[NBPM_PROCESSBLOCK];
              select * from [dbo].[NBPM_TRANSITION];
            */
        }
开发者ID:JackWangCUMT,项目名称:netbpm,代码行数:27,代码来源:HelloWorld1Test.cs

示例12: IsWaveFile

        /// <summary>
        /// 判断文件是否是音频文件
        /// </summary>
        /// <param name="file">需要判断的文件</param>
        /// <returns>返回bool类型值</returns>
        public static bool IsWaveFile(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = file.OpenRead();
                byte[] ware_FmtID = new byte[4];
                stream.Read(ware_FmtID, 0, 4);
                if (ware_FmtID[0] != 82 || ware_FmtID[1] != 73 || ware_FmtID[2] != 70 || ware_FmtID[3] != 70)
                {
                    return false;
                }
                stream.Seek(9, System.IO.SeekOrigin.Begin);

                stream.Read(ware_FmtID, 0, 4);

                if (ware_FmtID[0] != 65 || ware_FmtID[1] != 86 || ware_FmtID[2] != 69 || ware_FmtID[3] != 102)
                {
                    return false;
                }
                return true;
            }
            catch (System.IO.IOException)
            {
                return false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
开发者ID:wangjianglin,项目名称:dotnet-core,代码行数:39,代码来源:WaveFile.cs

示例13: ModelInfo

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo) {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");

            if (!fileInfo.Exists)
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {

                using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
                    foreach (var entry in zip.Entries) {
                        if (entry.Name != ArtifactProvider.ManifestEntry) 
                            continue;

                        using (var stream = entry.Open()) {
                            Manifest = (Properties)Properties.Deserialize(stream);
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
开发者ID:lovethisgame,项目名称:SharpNL,代码行数:34,代码来源:ModelInfo.cs

示例14: OnFileCreated

        void OnFileCreated(object sender, FileSystemEventArgs e)
        {
            FileInfo lFile = new FileInfo(e.FullPath);
            if (lFile.Exists)
            {
                // schedule the processing on a different thread
                ThreadPool.QueueUserWorkItem(delegate
                {
                    while (true)
                    {
                        // wait 100 milliseconds between attempts to read
                        Thread.Sleep(TimeSpan.FromMilliseconds(100));
                        try
                        {
                            // try to open the file
                            lFile.OpenRead().Close();
                            break;
                        }
                        catch (IOException)
                        {
                            // if the file is still locked, keep trying
                            continue;
                        }
                    }

                    // the file can be opened successfully: raise the event
                    if (Created != null)
                        Created(this, e);
                });
            }
        }
开发者ID:andrewleith,项目名称:OrangeCloudSyncClient,代码行数:31,代码来源:FileWatcher.cs

示例15: KMPSearch

 /// <summary>
 /// 采用KMP算法进行搜索
 /// </summary>
 /// <param name="file"></param>
 /// <param name="data"></param>
 /// <param name="next"></param>
 /// <returns></returns>
 public long[] KMPSearch(FileInfo file, byte[] data, int[] next)
 {
     using (FileStream fileReader = file.OpenRead())
     {
         return KMP.Match(fileReader, data, next);
     }
 }
开发者ID:romhackingvn,项目名称:Alpha-Translation,代码行数:14,代码来源:FileDataSearch.cs


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