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


C# FileStream.ReadByte方法代码示例

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


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

示例1: getRegions

    // Read in from a binary file the number of regions and months to sample
    public int[] getRegions()
    {
        int[] var = new int[2];
        FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);

        var[0] = F.ReadByte();
        var[1] = F.ReadByte();

        return var;
    }
开发者ID:CharlieWeld,项目名称:CSharpLabs,代码行数:11,代码来源:RainfallFileInput.cs

示例2: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Make sure Dispose can be called");

        try
        {
            Stream stream = new FileStream(c_READ_FILE_NAME, FileMode.OpenOrCreate);

            stream.Dispose();

            try
            {
                stream.ReadByte();

                TestLibrary.TestFramework.LogError("001.1", "Call Dispose takes no effect");
                retVal = false;
            }
            catch (ObjectDisposedException)
            { 
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:l1183479157,项目名称:coreclr,代码行数:32,代码来源:streamdispose1.cs

示例3: Read

 public async Task Read(bool useAsync, int bufferSize, int totalSize)
 {
     byte[] bytes = new byte[bufferSize];
     // Actual file size may be slightly over the desired size due to rounding if totalSize % readSize != 0
     int innerIterations = totalSize / bufferSize;
     string filePath = CreateFile(innerIterations * bufferSize);
     foreach (var iteration in Benchmark.Iterations)
     {
         if (useAsync)
         {
             using (FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous))
             using (iteration.StartMeasurement())
                 await ReadAsyncCore(reader, innerIterations, bytes);
         }
         else
         {
             using (FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.None))
             using (iteration.StartMeasurement())
             {
                 if (bufferSize == 1)
                     for (int i = 0; i < totalSize; i++)
                         reader.ReadByte();
                 else
                     for (int i = 0; i < innerIterations; i++)
                         reader.Read(bytes, 0, bytes.Length);
             }
         }
     }
     File.Delete(filePath);
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:30,代码来源:Perf.FileStream.cs

示例4: Main

 static void Main()
 {
     FileStream stream = new FileStream("pic.jpg", FileMode.Open);
     FileStream secondStream = new FileStream("NewPic.jpg", FileMode.Create);
     try
     {
         int readByte = stream.ReadByte();
         while (readByte != -1)
         {
             secondStream.WriteByte((byte)readByte);
             readByte = stream.ReadByte();
         }
     }
     finally
     {
         stream.Close();
         secondStream.Close();
     }
 }
开发者ID:T316,项目名称:AdvancedCSharp,代码行数:19,代码来源:CopyBinaryFile.cs

示例5: FlushAfterReading

 public async Task FlushAfterReading(bool? flushToDisk)
 {
     string fileName = GetTestFilePath();
     File.WriteAllBytes(fileName, TestBuffer);
     using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 2))
     {
         Assert.Equal(TestBuffer[0], fs.ReadByte());
         await fs.FlushAsync();
     }
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:10,代码来源:FlushAsync.cs

示例6: Main

 static void Main()
 {
     using (var file = new FileStream("../../../view.jpg", FileMode.Open))
     {
         using (var copyFile = new FileStream("../../CopyView.jpg", FileMode.Create))
         {
             while (file.Position < file.Length)
             {
                 copyFile.WriteByte((byte)file.ReadByte());
             }
         }
     }
 }
开发者ID:teodory,项目名称:SoftUni-Homeworks,代码行数:13,代码来源:Problem4.cs

示例7: Main

 public static void Main(string[] args)
 {
     if (args.Length == 1) {
       Stream input = new FileStream(args[0], FileMode.Open);
       int i;
       while((i = input.ReadByte()) != -1)
     Console.Write(i + " ");
       input.Close();
     }else {
       int i;
       while((i = Console.In.Read()) != -1)
     Console.Write(i + " ");
     }
 }
开发者ID:JnS-Software-LLC,项目名称:CSC153,代码行数:14,代码来源:ReadBytes.cs

示例8: Init

    private void Init(string ioPath, ref HashSet<string> refHashSet, bool isMd5Mode)
    {
        _isMD5 = isMd5Mode;
        _hashSet = refHashSet;

        if (File.Exists(ioPath))
        {
            using (var readStream = new FileStream(ioPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
            {
                // Read
                var sb = new StringBuilder();
                var sLength = readStream.Length;
                var lastNewlinePos = 0L;
                while (readStream.Position < sLength)
                {
                    var c = (char)readStream.ReadByte();
                    if (c == '\n')
                    {
                        var getStr = sb.ToString().Trim();
                        _hashSet.Add(getStr); // 过滤换行符 '\r'等
                        sb.Length = 0; // clear
                        lastNewlinePos = readStream.Position;
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                if (lastNewlinePos != readStream.Position)
                {
                    // 抹掉最后一行!
                    // 最后一行,故意忽略掉,为什么?
                    // 因为上次程序有可能写到一半中途退出!  造成最后一行写入错误!超坑的!
                    readStream.SetLength(lastNewlinePos);  // 拦截到换行处
                }
            }  
        }
        _appendStream = new FileStream(ioPath, FileMode.Append, FileAccess.Write, FileShare.Read);
        _writer = new StreamWriter(_appendStream);

        _writer.AutoFlush = true; // 自动刷新, 每一次都是一个写入,会降低系统性能,但大大增加可靠性
    }
开发者ID:henry-yuxi,项目名称:CosmosEngine,代码行数:43,代码来源:CFileCacheList.cs

示例9: EncryptFile

    public static string EncryptFile(string filePath)
    {
        Debug.Log("Encrypting");
        var output = String.Empty;
        try
        {
            using (RijndaelManaged aes = new RijndaelManaged())
            {
                byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

                byte[] IV = ASCIIEncoding.UTF8.GetBytes(vkey);

                using (FileStream fsCrypt = new FileStream(filePath + "uSave.dat", FileMode.Create))
                {
                    using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
                    {
                        using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (FileStream fsIn = new FileStream(filePath + "eSave.dat", FileMode.Open))
                            {
                                int data;

                                while ((data = fsIn.ReadByte()) != -1)
                                {
                                    cs.WriteByte((byte)data);
                                }
                                output = cs.ToString();
                            }
                        }
                    }
                }
            }
            //File.Delete(filePath + "uSave.dat");
        }
        catch{} // failed to encrypt file

        return output;
    }
开发者ID:Daloupe,项目名称:Syzygy_Git,代码行数:38,代码来源:Encryption.cs

示例10: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Dispose interface is implemented by Stream class...");

        try
        {
            Stream stream = new FileStream(c_FILE_NAME,FileMode.OpenOrCreate);
            IDisposable idisp = stream as IDisposable;

            stream.Dispose();

            try
            {
                stream.ReadByte();

                TestLibrary.TestFramework.LogError("001","The stream object is not disposed yet!");
                retVal = false;
            }
            catch (ObjectDisposedException)
            { 
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002","Unexpected exception occurs: " + e);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:31,代码来源:idisposabledispose.cs

示例11: PutItem

    public HttpStatusCode PutItem(int key, string entityData)
    {
        HttpStatusCode status = HttpStatusCode.OK;

        FileStream resourceStream = null;

        try
        {
          if (entityData.Length > _blockSize)
          {
        status = HttpStatusCode.RequestEntityTooLarge;
          }
          else if (entityData[0] != '{' || entityData[entityData.Length - 1] != '}')
          {
        status = HttpStatusCode.BadRequest;
          }

          if (status == HttpStatusCode.OK)
          {
        lock (SyncRoot)
        {
          FileInfo resourceInfo = new FileInfo(_restdFile);
          long entityCount = (resourceInfo.Length - 64) / _blockSize;

          if (key >= entityCount)
          {
            status = HttpStatusCode.NotFound;
          }
          else
          {
            long insertOffset = 64 + _byteOrderMarkSize + key * _blockSize;

            resourceStream = new FileStream(_restdFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

            long insertPos = resourceStream.Seek(insertOffset, SeekOrigin.Begin);

            if (resourceStream.ReadByte() != (byte)'{')
            {
              status = HttpStatusCode.NotFound;
            }
            else
            {
              insertPos = resourceStream.Seek(-1, SeekOrigin.Current);

              StreamWriter resourceWriter = new StreamWriter(resourceStream);
              resourceWriter.Write(entityData);
              resourceWriter.Write(",");
              resourceWriter.Write(new string(' ', _blockSize - entityData.Length - 1));
              resourceWriter.Flush();
              resourceStream.Close();
              resourceStream = null;
            }
          }
        }
          }
        }
        catch (Exception ex)
        {
          Trace.WriteLine(ex.Message);
          status = HttpStatusCode.InternalServerError;
        }

        return status;
    }
开发者ID:ryanttb,项目名称:restd,代码行数:64,代码来源:ORestd.cs

示例12: File_AllDataCopied

        public async Task File_AllDataCopied(
            Func<string, Stream> createDestinationStream,
            bool useAsync, bool preRead, bool preWrite, bool exposeHandle, bool cancelable,
            int bufferSize, int writeSize, int numWrites)
        {
            // Create the expected data
            long totalLength = writeSize * numWrites;
            var expectedData = new byte[totalLength];
            new Random(42).NextBytes(expectedData);

            // Write it out into the source file
            string srcPath = GetTestFilePath();
            File.WriteAllBytes(srcPath, expectedData);

            string dstPath = GetTestFilePath();
            using (FileStream src = new FileStream(srcPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
            using (Stream dst = createDestinationStream(dstPath))
            {
                // If configured to expose the handle, do so.  This influences the stream's need to ensure the position is in sync.
                if (exposeHandle)
                {
                    var ignored = src.SafeFileHandle;
                }

                // If configured to "preWrite", do a write before we start reading.
                if (preWrite)
                {
                    src.Write(new byte[] { 42 }, 0, 1);
                    dst.Write(new byte[] { 42 }, 0, 1);
                    expectedData[0] = 42;
                }

                // If configured to "preRead", read one byte from the source prior to the CopyToAsync.
                // This helps test what happens when there's already data in the buffer, when the position
                // isn't starting at zero, etc.
                if (preRead)
                {
                    int initialByte = src.ReadByte();
                    if (initialByte >= 0)
                    {
                        dst.WriteByte((byte)initialByte);
                    }
                }

                // Do the copy
                await src.CopyToAsync(dst, writeSize, cancelable ? new CancellationTokenSource().Token : CancellationToken.None);
                dst.Flush();

                // Make sure we're at the end of the source file
                Assert.Equal(src.Length, src.Position);

                // Verify the copied data
                dst.Position = 0;
                var result = new MemoryStream();
                dst.CopyTo(result);
                byte[] actualData = result.ToArray();
                Assert.Equal(expectedData.Length, actualData.Length);
                Assert.Equal<byte>(expectedData, actualData);
            }
        }
开发者ID:shmao,项目名称:corefx,代码行数:60,代码来源:CopyToAsync.cs

示例13: SendFileProtocol

    //The Coroutine that sends the file
    private IEnumerator SendFileProtocol(FileTransferInfo transferInfo, float timeOutTime)
    {
        //Send setup informations to the client
        object[] setupParameters = new object[5] { transferInfo.Path, transferInfo.Server.ID, transferInfo.TotalBytes, transferInfo.BytesPerRpc, transferInfo.Id };
        photonView.RPC("RpcSetupTransferInfo", transferInfo.Client, setupParameters);
        //Wait until the client is ready
        float startTime = Time.time;
        bool clientReady = false;
        bool timeOut = false;
        do
        {
            if (transferInfo.ClientReady)
                clientReady = true;
            else if (Time.time - startTime >= timeOutTime)
                timeOut = true;
            yield return new WaitForSeconds(SecondsBetweenClientReadyCheck);
        } while (!clientReady && !timeOut);

        if (timeOut) //If there is no response from the client
        {
            OnFileUploadFailed(transferInfo, "Timeout: no response from the client");
        }
        else //Else, send the file
        {
            //Start sending the file
            List<byte> bytePacket = new List<byte>();
            int step = 0;
            using (FileStream fileStream = new FileStream(transferInfo.Path, FileMode.Open))
            {
                for (int i = 0; i < fileStream.Length; i++)
                {
                    int thisByte = fileStream.ReadByte();
                    bytePacket.Add(Convert.ToByte(thisByte));

                    if (bytePacket.Count == transferInfo.BytesPerRpc || i == fileStream.Length - 1) //If reached max byte per packet or end of the stream
                    {
                        //Send the current byte packet to the client
                        object[] transferParameters = new object[4] { PhotonNetwork.player.ID, transferInfo.Id, step, bytePacket.ToArray() };
                        photonView.RPC("RpcTransferBytes", transferInfo.Client, transferParameters);
                        transferInfo.SentBytes += bytePacket.Count;
                        bytePacket.Clear();
                        step++;
                        yield return new WaitForSeconds((float)1 / transferInfo.RpcPerSecond);
                    }
                }
            }

            if (OnFileUploaded != null)
            {
                OnFileUploaded(transferInfo);
            }
        }
    }
开发者ID:FrenchKrab,项目名称:KrabyPhoton,代码行数:54,代码来源:KrabyFileTransfer.cs

示例14: Encrypt

        public void Encrypt(string inf, string outf, int e)
        {
            //based on e we decide which encryption that we are
            //going to use for the virus. Since C# had a crypto
            //package I thought we try those out.
            if (e == 1) {
                try {
                    string p = getKey();

                    if (p.Length > 8)
                        p = p.Substring(0, 8);
                    else if (p.Length < 8) {
                        int add = 8 - p.Length;
                        for (int i = 0; i < add; i++)
                            p = p + i;
                    }
                    UnicodeEncoding UE = new UnicodeEncoding();
                    byte[] key = UE.GetBytes(p);

                    FileStream fsc = new FileStream(outf, FileMode.Create);
                    RijndaelManaged cr = new RijndaelManaged();
                    CryptoStream cs = new CryptoStream(fsc, cr.CreateEncryptor(key, key), CryptoStreamMode.Write);
                    FileStream fsIn = new FileStream(inf, FileMode.Open);
                    int d;
                    while ((d = fsIn.ReadByte()) != -1) {
                        cs.WriteByte((byte)d);
                    }
                    fsIn.Close();
                    cs.Close();
                    fsc.Close();

                } catch { }

            } else {
                try {

                    byte[] b = read(inf);
                    byte[] key = Convert.FromBase64String(getKey());
                    byte[] IV = Convert.FromBase64String(getIV());

                    FileStream fs = File.Open(outf, FileMode.OpenOrCreate);
                    CryptoStream cs = new CryptoStream(fs, new TripleDESCryptoServiceProvider().CreateEncryptor(key, IV), CryptoStreamMode.Write);
                    BinaryWriter bw = new BinaryWriter(cs);
                    bw.Write(b);
                    bw.Close();
                    cs.Close();
                    fs.Close();

                } catch { }
            }
        }
开发者ID:cyberthreats,项目名称:malware-source-loki,代码行数:51,代码来源:Loki.cs

示例15: ParseNoteOffEvent

    MIDINote ParseNoteOffEvent(FileStream inFile, MIDIEvent midi_event)
    {
        MIDINote note;

        if(inFile != null){
            note = new MIDINote(midi_event);
            note.note = (UInt32)inFile.ReadByte();
            note.velocity = (UInt32)inFile.ReadByte();
        }else{
            note = (MIDINote)midi_event;
        }
        if(this.currentNotes.ContainsKey(note.note) ){
            this.currentNotes[note.note].duration = CurrentTime() - note.absoluteStartTime;
            this.currentNotes.Remove(note.note);
        }else{
            Debug.LogWarning("try to access not existing note: "  + note.note);
        }

        return note;
    }
开发者ID:alexandrovsky,项目名称:AudioTest01,代码行数:20,代码来源:MIDI.cs


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