System.IO.FileStream.Read(byte[], int, int)

Here are the examples of the csharp api System.IO.FileStream.Read(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1113 Examples 7

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

public static byte[] ReadFile(string path) {
				if (File.Exists(path)) {
					string destFileName = Path.GetTempFileName();
					File.Copy(path, destFileName, true);
					int read = 0;
					byte[] data = new byte[1024];
					using (MemoryStream ms = new MemoryStream()) {
						using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) {
							do {
								read = fs.Read(data, 0, data.Length);
								if (read <= 0) break;
								ms.Write(data, 0, read);
							} while (true);
						}
						File.Delete(destFileName);
						data = ms.ToArray();
					}
					return data;
				}
				return new byte[] { };
			}

19 View Source File : FileUtil.cs
License : MIT License
Project Creator : 404Lcc

public static byte[] Getreplacedet(string path)
        {
            if (File.Exists(path))
            {
                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    byte[] bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    return bytes;
                }
            }
            return null;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : 5minlab

public static void WriteFile(this HttpListenerResponse response, string path, string type = "application/octet-stream", bool download = false) {
            using (FileStream fs = File.OpenRead(path)) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.ContentLength64 = fs.Length;
                response.ContentType = type;
                if (download)
                    response.AddHeader("Content-disposition", string.Format("attachment; filename={0}", Path.GetFileName(path)));

                byte[] buffer = new byte[64 * 1024];
                int read;
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) {
                    // FIXME required?
                    System.Threading.Thread.Sleep(0);
                    response.OutputStream.Write(buffer, 0, read);
                }
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetNumber(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadString()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/string");

            foreach (var file in files)
            {
                var value = Path.GetFileNameWithoutExtension(file);
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetString(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadArray()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/array.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);
                var arrayData = new List<object> { 1.0d, 2.0d, 3.0d, 4.0d, "a", "asdf", "eee" };
                replacedert.IsTrue(reader.TryGetStrictArray(data, out var dataRead, out var consumed));
                replacedert.IsTrue(arrayData.SequenceEqual(dataRead));
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadDate()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/date.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetDate(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead.Year, 2019);
                replacedert.AreEqual(dataRead.Month, 2);
                replacedert.AreEqual(dataRead.Day, 11);
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadLongString()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/longstring.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetLongString(data, out var dataRead, out var consumed));
                replacedert.AreEqual(string.Concat(Enumerable.Repeat("abc", 32767)), dataRead);
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNull()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/null.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetNull(data, out var dataRead, out var consumed));
                replacedert.AreEqual(null, dataRead);
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNull2()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/null.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetObject(data, out var dataRead, out var consumed));
                replacedert.AreEqual(null, dataRead);
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadXml()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/xml.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetXmlDoreplacedent(data, out var dataRead, out var consumed));
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("a").Count, 0);
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("b").Count, 0);
                replacedert.IsNotNull(dataRead.GetElementsByTagName("b")[0].Attributes["value"], "1");
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadUndefined()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/undefined.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetUndefined(data, out var dataRead, out var consumed));
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadEcmaArray()
        {
            var reader = new Amf0Reader();

            // pyamf has a bug about element count of ecma array
            // https://github.com/hydralabs/pyamf/blob/master/pyamf/amf0.py#L567
            reader.StrictMode = false;

            using (var f = new FileStream("../../../../samples/amf0/misc/ecmaarray.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetEcmaArray(data, out var dataRead, out var consumed));
                replacedert.IsTrue(dataRead.SequenceEqual(new Dictionary<string, object>() { ["a"] = 1.0d, ["b"] = "a", ["c"] = "a" }));
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadObject()
        {
            var reader = new Amf0Reader();

            // pyamf has a bug about element count of ecma array
            // https://github.com/hydralabs/pyamf/blob/master/pyamf/amf0.py#L567
            reader.StrictMode = false;

            using (var f = new FileStream("../../../../samples/amf0/misc/object.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetObject(data, out var dataRead, out var consumed));
                replacedert.IsTrue(dataRead.Fields.SequenceEqual(new Dictionary<string, object>() { ["a"] = "b", ["c"] = 1.0 }));
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestPacket()
        {
            var reader = new Amf0Reader();
            reader.RegisterType<RemotingMessage>();
            reader.StrictMode = false;
            using (var file = new FileStream("../../../../samples/amf0/misc/packet.amf0", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);
                replacedert.IsTrue(reader.TryGetPacket(data, out var headers, out var messages, out var consumed));
                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadPacket1()
        {
            var reader = new Amf0Reader();
            reader.RegisterType<RemotingMessage>();
            reader.StrictMode = false;
            using (var file = new FileStream("../../../../samples/amf3/misc/packet.amf3", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);
                replacedert.IsTrue(reader.TryGetPacket(data, out var headers, out var messages, out var consumed));
                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestUndefined()
        {
            var reader = new Amf3Reader();
            reader.RegisterTypedObject<RemotingMessage>();

            using (var file = new FileStream("../../../../samples/amf3/misc/undefined.amf3", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);
                replacedert.IsTrue(reader.TryGetUndefined(data, out var value, out var consumed));
                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestNull()
        {
            var reader = new Amf3Reader();
            reader.RegisterTypedObject<RemotingMessage>();

            using (var file = new FileStream("../../../../samples/amf3/misc/null.amf3", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);
                replacedert.IsTrue(reader.TryGetNull(data, out var value, out var consumed));
                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestDate()
        {
            var reader = new Amf3Reader();
            reader.RegisterTypedObject<RemotingMessage>();

            using (var file = new FileStream("../../../../samples/amf3/misc/date.amf3", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);
                replacedert.IsTrue(reader.TryGetDate(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead.Year, 2019);
                replacedert.AreEqual(dataRead.Month, 2);
                replacedert.AreEqual(dataRead.Day, 11);
                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadObject()
        {
            var reader = new Amf3Reader();

            using (var file = new FileStream("../../../../samples/amf3/misc/object.amf3", FileMode.Open))
            {
                var data = new byte[file.Length];
                file.Read(data);

                replacedert.IsTrue(reader.TryGetObject(data, out var dataRead, out var consumed));
                var obj = (AmfObject)dataRead;
                replacedert.IsTrue(obj.Fields.SequenceEqual(new Dictionary<string, object>() { ["t1"] = 1.0, ["t2"] = "aaa", ["t3"] = "aac" }));
                replacedert.AreEqual(obj.DynamicFields["td"], "aacf");
                var td2 = (Dictionary<object, object>)obj.DynamicFields["td2"];

                var keyList = td2.Keys.ToList();
                var key0 = (string)keyList[0];
                var key1 = (double)keyList[1];
                var key2 = (Vector<double>)keyList[2];
                var key3 = (Vector<uint>)keyList[3];

                var v0 = (double)td2[key0];
                var v1 = (Vector<int>)td2[key1];
                var v2 = (Vector<int>)td2[key2];
                var v3 = (Vector<int>)td2[key3];

                replacedert.AreEqual(key0, "test");
                replacedert.AreEqual(key1, 3);
                replacedert.AreEqual(key2[0], 3.0);
                replacedert.AreEqual(key2[1], 4.0);
                replacedert.AreEqual(key2[2], 5.0);
                replacedert.AreEqual(key3[0], (uint)32);
                replacedert.AreEqual(key3[1], (uint)43);
                replacedert.AreEqual(key3[2], (uint)54);
                replacedert.AreEqual(v0, 1);
                replacedert.AreEqual(v1[0], 2);
                replacedert.AreEqual(v1[1], 3);
                replacedert.AreEqual(v1[2], 4);
                replacedert.AreEqual(v2[0], 2);
                replacedert.AreEqual(v2[1], 3);
                replacedert.AreEqual(v2[2], 4);
                replacedert.AreEqual(v3[0], 2);
                replacedert.AreEqual(v3[1], 3);
                replacedert.AreEqual(v3[2], 4);


                replacedert.AreEqual(consumed, file.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadXml()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/xml.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetXml(data, out var dataRead, out var consumed));
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("a").Count, 0);
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("b").Count, 0);
                replacedert.IsNotNull(dataRead.GetElementsByTagName("b")[0].Attributes["value"], "1");
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadXmlDoreplacedent()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/xml_doreplacedent.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetXmlDoreplacedent(data, out var dataRead, out var consumed));
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("a").Count, 0);
                replacedert.AreEqual(dataRead.GetElementsByTagName("a")[0].Attributes["value"].Value, "1");
                replacedert.AreNotEqual(dataRead.GetElementsByTagName("b").Count, 0);
                replacedert.AreEqual(dataRead.GetElementsByTagName("b")[0].FirstChild.Value, "2");
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadArray()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/array.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetArray(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead[0], 1.0);
                replacedert.AreEqual(dataRead[1], "aa");
                var v = (Vector<int>)dataRead["aa"];
                replacedert.AreEqual(v[0], 1);
                replacedert.AreEqual(v[1], 2);
                replacedert.AreEqual(v[2], 3);
                replacedert.IsInstanceOfType(dataRead["bb"], typeof(Dictionary<object, object>));

                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadDictionary()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/dictionary.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetDictionary(data, out var dataRead, out var consumed));
                var keys = dataRead.Keys.ToList();
                var k0 = keys[0];
                var k2 = (AmfObject)keys[1];
                var k1 = keys[2];

                var v0 = dataRead[k0];
                var v1 = (Vector<int>)dataRead[k1];
                var v2 = (Vector<int>)dataRead[k2];

                replacedert.AreEqual(k0, "test");
                replacedert.AreEqual(k1, 3.0);

                replacedert.AreEqual(k2.Fields["t1"], 1.0);
                replacedert.AreEqual(k2.Fields["t2"], "aaa");
                replacedert.AreEqual(k2.Fields["t3"], "aac");

                replacedert.AreEqual(v0, 1.0);
                replacedert.AreEqual(v1[0], 2);
                replacedert.AreEqual(v1[1], 3);
                replacedert.AreEqual(v1[2], 4);

                replacedert.AreEqual(v2[0], 2);
                replacedert.AreEqual(v2[1], 3);
                replacedert.AreEqual(v2[2], 4);

                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadVectorInt()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/vector_int.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetVectorInt(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead[0], 1);
                replacedert.AreEqual(dataRead[1], 2);
                replacedert.AreEqual(dataRead[2], 3);

                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadVectorUint()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/vector_uint.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetVectorUint(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead[0], (uint)1);
                replacedert.AreEqual(dataRead[1], (uint)2);
                replacedert.AreEqual(dataRead[2], (uint)3);

                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadVectorDouble()
        {
            var reader = new Amf3Reader();


            using (var f = new FileStream("../../../../samples/amf3/misc/vector_double.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetVectorDouble(data, out var dataRead, out var consumed));
                replacedert.AreEqual(dataRead[0], (double)1);
                replacedert.AreEqual(dataRead[1], (double)2);
                replacedert.AreEqual(dataRead[2], (double)3);

                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadByteArray()
        {
            var reader = new Amf3Reader();

            using (var f = new FileStream("../../../../samples/amf3/misc/bytearray.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetByteArray(data, out var dataRead, out var consumed));

                replacedert.AreEqual(dataRead[0], (byte)1);
                replacedert.AreEqual(dataRead[1], (byte)2);
                replacedert.AreEqual(dataRead[2], (byte)3);

                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadExternalizable()
        {
            var reader = new Amf3Reader();
            reader.RegisterExternalizable<iexternalizable>();
            using (var f = new FileStream("../../../../samples/amf3/misc/externalizable.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetObject(data, out var dataRead, out var consumed));
                var ie = (iexternalizable)dataRead;
                replacedert.AreEqual(ie.v1, 3.14);
                replacedert.AreEqual(ie.v2, 333);

                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadNumber()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/number");

            foreach (var file in files)
            {
                var value = double.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetDouble(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadInteger()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/intenger");

            foreach (var file in files)
            {
                var value = uint.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetUInt29(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadString()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/string");

            foreach (var file in files)
            {
                var value = Path.GetFileNameWithoutExtension(file);
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetString(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadVectorTyped()
        {
            var reader = new Amf3Reader();
            reader.RegisterTypedObject<TestCls>();

            using (var f = new FileStream("../../../../samples/amf3/misc/vector_typted_object.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetVectorObject(data, out var dataRead, out var consumed));

                var v = (Vector<TestCls>)dataRead;

                var t = v[0];
                replacedert.AreEqual(t.T1, 1.0);
                replacedert.AreEqual(t.T2, "aaa");
                replacedert.AreEqual(t.T3, "aac");
                replacedert.AreEqual(t.t4[0], 1);
                replacedert.AreEqual(t.t4[1], 2);
                replacedert.AreEqual(t.t4[2], 3);

                var t2 = v[1];
                replacedert.AreEqual(t2.T1, 1.0);
                replacedert.AreEqual(t2.T2, "aaa");
                replacedert.AreEqual(t2.T3, "aac");
                replacedert.AreEqual(t2.t4[0], 1);
                replacedert.AreEqual(t2.t4[1], 2);
                replacedert.AreEqual(t2.t4[2], 3);
                replacedert.AreEqual(consumed, f.Length);
            }
        }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadVectorAny()
        {
            var reader = new Amf3Reader();

            using (var f = new FileStream("../../../../samples/amf3/misc/vector_any_object.amf3", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);

                replacedert.IsTrue(reader.TryGetVectorObject(data, out var dataRead, out var consumed));

                var v = (Vector<object>)dataRead;
                var obj = (AmfObject)v[0];

                replacedert.AreEqual(obj.Fields["t1"], 1.0);
                replacedert.AreEqual(obj.Fields["t2"], "aaa");
                replacedert.AreEqual(obj.Fields["t3"], "aac");

                replacedert.AreEqual(v[1], 2.0);
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : WebServer.cs
License : Apache License 2.0
Project Creator : A7ocin

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 View Source File : RepositorySaveData.cs
License : Apache License 2.0
Project Creator : AantCoder

public byte[] LoadPlayerData(string login, int numberSave)
        {
            if (numberSave < 1 || numberSave > CountSaveDataPlayer) return null;

            var fileName = GetFileNameBase(login) + numberSave.ToString();

            var info = new FileInfo(fileName);
            if (!info.Exists || info.Length < 10) return null;

            //читаем содержимое
            bool readAsXml;
            using (var file = File.OpenRead(fileName))
            {
                var buff = new byte[10];
                file.Read(buff, 0, 10);
                readAsXml = Encoding.ASCII.GetString(buff, 0, 10).Contains("<?xml");
            }
            //считываем текст как xml сейва или как сжатого zip'а
            var saveFileData = File.ReadAllBytes(fileName);
            if (readAsXml)
            {
                return saveFileData;
            }
            else
            {
                return GZip.UnzipByteByte(saveFileData);
            }
        }

19 View Source File : Shapefile.cs
License : Microsoft Public License
Project Creator : abfo

public void Open(string path)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("Shapefile");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (path.Length <= 0)
            {
                throw new ArgumentException("path parameter is empty", "path");
            }

            _shapefileMainPath = Path.ChangeExtension(path, MainPathExtension);
            _shapefileIndexPath = Path.ChangeExtension(path, IndexPathExtension);
            _shapefileDbasePath = Path.ChangeExtension(path, DbasePathExtension);

            if (!File.Exists(_shapefileMainPath))
            {
                throw new FileNotFoundException("Shapefile main file not found", _shapefileMainPath);
            }
            if (!File.Exists(_shapefileIndexPath))
            {
                throw new FileNotFoundException("Shapefile index file not found", _shapefileIndexPath);
            }
            if (!File.Exists(_shapefileDbasePath))
            {
                throw new FileNotFoundException("Shapefile dBase file not found", _shapefileDbasePath);
            }

            _mainStream = File.Open(_shapefileMainPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            _indexStream = File.Open(_shapefileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read);

            if (_mainStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile main file does not contain a valid header");
            }

            if (_indexStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile index file does not contain a valid header");
            }

            // read in and parse the headers
            byte[] headerBytes = new byte[Header.HeaderLength];
            _mainStream.Read(headerBytes, 0, Header.HeaderLength);
            _mainHeader = new Header(headerBytes);
            _indexStream.Read(headerBytes, 0, Header.HeaderLength);
            _indexHeader = new Header(headerBytes);

            // set properties from the main header
            _type = _mainHeader.ShapeType;
            _boundingBox = new RectangleD(_mainHeader.XMin, _mainHeader.YMin, _mainHeader.XMax, _mainHeader.YMax);

            // index header length is in 16-bit words, including the header - number of 
            // shapes is the number of records (each 4 workds long) after subtracting the header bytes
            _count = (_indexHeader.FileLength - (Header.HeaderLength / 2)) / 4;

            // open the metadata database
            OpenDb();

            _opened = true;
        }

19 View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<GltfObject> ImportGltfObjectFromPathAsync(string uri)
        {
            if (!SyncContextUtility.IsMainThread)
            {
                Debug.LogError("ImportGltfObjectFromPathAsync must be called from the main thread!");
                return null;
            }

            if (string.IsNullOrWhiteSpace(uri))
            {
                Debug.LogError("Uri is not valid.");
                return null;
            }

            GltfObject gltfObject;
            bool useBackgroundThread = Application.isPlaying;

            if (useBackgroundThread) { await BackgroundThread; }

            if (uri.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase))
            {
                string gltfJson = File.ReadAllText(uri);

                gltfObject = GetGltfObjectFromJson(gltfJson);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed load Gltf Object from json schema.");
                    return null;
                }
            }
            else if (uri.EndsWith(".glb", StringComparison.OrdinalIgnoreCase))
            {
                byte[] glbData;

#if WINDOWS_UWP

                if (useBackgroundThread)
                {
                    try
                    {
                        var storageFile = await StorageFile.GetFileFromPathAsync(uri);

                        if (storageFile == null)
                        {
                            Debug.LogError($"Failed to locate .glb file at {uri}");
                            return null;
                        }

                        var buffer = await FileIO.ReadBufferAsync(storageFile);

                        using (DataReader dataReader = DataReader.FromBuffer(buffer))
                        {
                            glbData = new byte[buffer.Length];
                            dataReader.ReadBytes(glbData);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.Message);
                        return null;
                    }
                }
                else
                {
                    glbData = UnityEngine.Windows.File.ReadAllBytes(uri);
                }
#else
                using (FileStream stream = File.Open(uri, FileMode.Open))
                {
                    glbData = new byte[stream.Length];

                    if (useBackgroundThread)
                    {
                        await stream.ReadAsync(glbData, 0, (int)stream.Length);
                    }
                    else
                    {
                        stream.Read(glbData, 0, (int)stream.Length);
                    }
                }
#endif

                gltfObject = GetGltfObjectFromGlb(glbData);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed to load GlTF Object from .glb!");
                    return null;
                }
            }
            else
            {
                Debug.LogError("Unsupported file name extension.");
                return null;
            }

            gltfObject.Uri = uri;

            try
            {
                gltfObject.Name = Path.GetFileNameWithoutExtension(uri);
            }
            catch (ArgumentException)
            {
                Debug.LogWarning("Uri contained invalid character");
                gltfObject.Name = DefaultObjectName;
            }

            gltfObject.UseBackgroundThread = useBackgroundThread;
            await gltfObject.ConstructAsync();

            if (gltfObject.GameObjectReference == null)
            {
                Debug.LogError("Failed to construct Gltf Object.");
            }

            if (useBackgroundThread) { await Update; }

            return gltfObject;
        }

19 View Source File : ConstructGltf.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture)
        {
            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            if (gltfTexture.source >= 0)
            {
                GltfImage gltfImage = gltfObject.images[gltfTexture.source];

                byte[] imageData = null;
                Texture2D texture = null;

                if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri))
                {
                    var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
                    var path = Path.Combine(parentDirectory, gltfImage.uri);

#if UNITY_EDITOR
                    if (gltfObject.UseBackgroundThread) await Update;
                    var projectPath = Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "replacedets");
                    texture = UnityEditor.replacedetDatabase.LoadreplacedetAtPath<Texture2D>(projectPath);

                    if (gltfObject.UseBackgroundThread) await BackgroundThread;
#endif

                    if (texture == null)
                    {
#if WINDOWS_UWP
                        if (gltfObject.UseBackgroundThread)
                        {
                            try
                            {
                                var storageFile = await StorageFile.GetFileFromPathAsync(path);

                                if (storageFile != null)
                                {

                                    var buffer = await FileIO.ReadBufferAsync(storageFile);

                                    using (DataReader dataReader = DataReader.FromBuffer(buffer))
                                    {
                                        imageData = new byte[buffer.Length];
                                        dataReader.ReadBytes(imageData);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogError(e.Message);
                            }
                        }
                        else
                        {
                            imageData = UnityEngine.Windows.File.ReadAllBytes(path);
                        }
#else
                        using (FileStream stream = File.Open(path, FileMode.Open))
                        {
                            imageData = new byte[stream.Length];

                            if (gltfObject.UseBackgroundThread)
                            {
                                await stream.ReadAsync(imageData, 0, (int)stream.Length);
                            }
                            else
                            {
                                stream.Read(imageData, 0, (int)stream.Length);
                            }
                        }
#endif
                    }
                }
                else
                {
                    var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView];
                    imageData = new byte[imageBufferView.byteLength];
                    Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length);
                }

                if (texture == null)
                {
                    if (gltfObject.UseBackgroundThread) await Update;
                    // TODO Load texture async
                    texture = new Texture2D(2, 2);
                    gltfImage.Texture = texture;
                    gltfImage.Texture.LoadImage(imageData);
                }
                else
                {
                    gltfImage.Texture = texture;
                }

                gltfTexture.Texture = texture;

                if (gltfObject.UseBackgroundThread) await BackgroundThread;
            }
        }

19 View Source File : DatReader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static byte[] ReadDat(FileStream stream, uint offset, uint size, uint blockSize)
        {
            var buffer = new byte[size];

            stream.Seek(offset, SeekOrigin.Begin);

            // Dat "file" is broken up into sectors that are not neccessarily congruous. Next address is stored in first four bytes of each sector.
            uint nextAddress = GetNextAddress(stream, 0);

            int bufferOffset = 0;

            while (size > 0)
            {
                if (size < blockSize)
                {
                    stream.Read(buffer, bufferOffset, Convert.ToInt32(size));
                    size = 0; // We know we've read the only/last sector, so just set this to zero to proceed.
                }
                else
                {
                    stream.Read(buffer, bufferOffset, Convert.ToInt32(blockSize) - 4); // Read in our sector into the buffer[]
                    bufferOffset += Convert.ToInt32(blockSize) - 4; // Adjust this so we know where in our buffer[] the next sector gets appended to
                    stream.Seek(nextAddress, SeekOrigin.Begin); // Move the file pointer to the start of the next sector we read above.
                    nextAddress = GetNextAddress(stream, 0); // Get the start location of the next sector.
                    size -= (blockSize - 4); // Decrease this by the amount of data we just read into buffer[] so we know how much more to go
                }
            }

            return buffer;
        }

19 View Source File : DatReader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static uint GetNextAddress(FileStream stream, int relOffset)
        {
            // The location of the start of the next sector is the first four bytes of the current sector. This should be 0x00000000 if no next sector.
            byte[] nextAddressBytes = new byte[4];

            if (relOffset != 0)
                stream.Seek(relOffset, SeekOrigin.Current); // To be used to back up 4 bytes from the origin at the start

            stream.Read(nextAddressBytes, 0, 4);

            return BitConverter.ToUInt32(nextAddressBytes, 0);
        }

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List<replacedem> _header, object _conmand = null)
      {
         #region 启动HTTP请求之前的初始化操作
         bool isget = false;
         if (_type == "GET")
         {
            isget = true;
         }

         if (isget)
         {
            if (_conmand is List<replacedem>)
            {
               List<replacedem> _conmand_ = (List<replacedem>)_conmand;

               string param = "";
               foreach (replacedem item in _conmand_)
               {
                  if (string.IsNullOrEmpty(param))
                  {
                     if (_url.Contains("?"))
                     {
                        param += "&" + item.Name + "=" + item.Value;
                     }
                     else
                     {
                        param = "?" + item.Name + "=" + item.Value;
                     }
                  }
                  else
                  {
                     param += "&" + item.Name + "=" + item.Value;
                  }
               }
               _url += param;
            }

         }
         Uri uri = null;
         try
         {
            uri = new Uri(_url);
         }
         catch { }
         #endregion
         if (uri != null)
         {
            //string _scheme = uri.Scheme.ToUpper();
            try
            {

               HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
               req.Proxy = null;
               req.Host = uri.Host;
               req.Method = _type;
               req.AllowAutoRedirect = false;
               bool isContentType = true;
               #region 设置请求头
               if (_header != null && _header.Count > 0)
               {
                  bool isnotHeader = true;
                  System.Collections.Specialized.NameValueCollection collection = null;

                  foreach (replacedem item in _header)
                  {
                     string _Lower_Name = item.Name.ToLower();
                     switch (_Lower_Name)
                     {
                        case "host":
                           req.Host = item.Value;
                           break;
                        case "accept":
                           req.Accept = item.Value;
                           break;
                        case "user-agent":
                           req.UserAgent = item.Value;
                           break;
                        case "referer":
                           req.Referer = item.Value;
                           break;
                        case "content-type":
                           isContentType = false;
                           req.ContentType = item.Value;
                           break;
                        case "cookie":
                           #region 设置COOKIE
                           string _cookie = item.Value;
                           CookieContainer cookie_container = new CookieContainer();
                           if (_cookie.IndexOf(";") >= 0)
                           {
                              string[] arrCookie = _cookie.Split(';');
                              //加载Cookie
                              //cookie_container.SetCookies(new Uri(url), cookie);
                              foreach (string sCookie in arrCookie)
                              {
                                 if (string.IsNullOrEmpty(sCookie))
                                 {
                                    continue;
                                 }
                                 if (sCookie.IndexOf("expires") > 0)
                                 {
                                    continue;
                                 }
                                 cookie_container.SetCookies(uri, sCookie);
                              }
                           }
                           else
                           {
                              cookie_container.SetCookies(uri, _cookie);
                           }
                           req.CookieContainer = cookie_container;
                           #endregion
                           break;
                        default:
                           if (isnotHeader && collection == null)
                           {
                              var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                              if (property != null)
                              {
                                 collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                              }
                              isnotHeader = false;
                           }
                           //设置对象的Header数据
                           if (collection != null)
                           {
                              collection[item.Name] = item.Value;
                           }
                           break;

                     }
                  }
               }
               #endregion

               #region 设置POST数据 
               if (!isget)
               {
                  if (_conmand != null)
                  {
                     if (_conmand is List<replacedem>)
                     {
                        List<replacedem> _conmand_ = (List<replacedem>)_conmand;
                        //POST参数
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = "";
                        foreach (replacedem item in _conmand_)
                        {
                           if (string.IsNullOrEmpty(param))
                           {
                              param = item.Name + "=" + item.Value;
                           }
                           else
                           {
                              param += "&" + item.Name + "=" + item.Value;
                           }
                        }

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }
                     else if (_conmand is string[])
                     {
                        try
                        {
                           string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                           byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                           byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                           req.ContentType = "multipart/form-data; boundary=" + boundary;


                           using (Stream reqStream = req.GetRequestStream())
                           {
                              string[] files = (string[])_conmand;

                              string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                              byte[] buff = new byte[1024];
                              for (int i = 0; i < files.Length; i++)
                              {
                                 string file = files[i];
                                 reqStream.Write(boundarybytes, 0, boundarybytes.Length);

                                 string contentType = MimeMappingProvider.Shared.GetMimeMapping(file);

                                 //string contentType = System.Web.MimeMapping.GetMimeMapping(file);

                                 //string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
                                 string header = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
                                 byte[] headerbytes = _encoding.GetBytes(header);
                                 reqStream.Write(headerbytes, 0, headerbytes.Length);

                                 using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                                 {

                                    int contentLen = fileStream.Read(buff, 0, buff.Length);

                                    int Value = contentLen;
                                    //文件上传开始
                                    //tProgress.Invoke(new Action(() =>
                                    //{
                                    //    tProgress.Maximum = (int)fileStream.Length;
                                    //    tProgress.Value = Value;
                                    //}));

                                    while (contentLen > 0)
                                    {
                                       //文件上传中

                                       reqStream.Write(buff, 0, contentLen);
                                       contentLen = fileStream.Read(buff, 0, buff.Length);
                                       Value += contentLen;

                                       //tProgress.Invoke(new Action(() =>
                                       //{
                                       //    tProgress.Value = Value;
                                       //}));
                                    }
                                 }
                              }

                              //文件上传结束
                              reqStream.Write(endbytes, 0, endbytes.Length);
                           }
                        }
                        catch
                        {
                           if (isContentType)
                           {
                              req.ContentType = null;
                           }
                           req.ContentLength = 0;
                        }

                     }
                     else
                     {
                        //POST参数 
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = _conmand.ToString();

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }

                  }
                  else
                  {
                     req.ContentLength = 0;
                  }
               }
               #endregion

               return req;
            }
            catch
            {
            }
         }
         return null;
      }

19 View Source File : SdkStreamManager.cs
License : MIT License
Project Creator : AElfProject

public Stream GetStream(replacedemblyName replacedemblyName)
        {
            // TODO: Handle version
            var path = Path.Combine(_sdkDir, replacedemblyName.Name + ".dll");
            if (!File.Exists(path))
            {
                var replacedembly = replacedembly.Load(replacedemblyName);

                if (replacedembly == null)
                    return null;

                path = replacedembly.Location;
            }

            if (!_cachedSdkStreams.TryGetValue(path, out var buffer))
            {
                using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)fs.Length;
                    buffer = new byte[length];
                    fs.Read(buffer, 0, length);
                    _cachedSdkStreams.TryAdd(path, buffer);
                }
            }

            return new MemoryStream(buffer);
        }

19 View Source File : Form_SteamID64_Editor.cs
License : MIT License
Project Creator : Aemony

private void ReadSteamID()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + "\\My Games\\NieR_Automata";
            dlg.Filter = "Data files (*.dat)|*.dat";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                filePath = dlg.FileName;

                if (filePath.Contains("SlotData"))
                {
                    // SlotData files stores the SteamID64 in offset 04-11, GameData and SystemData files stores the SteamID64 in offset 00-07
                    fileOffset = 4;
                }
                else
                {
                    fileOffset = 0;
                }
                
                try {
                    using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        stream.Position = fileOffset;
                        stream.Read(byteSteamID64, 0, 8);
                    }


                    // Convert to proper IDs.
                    // SteamID64 is stored as Little-Endian in the files, but as Intel is little-endian as well no reversal is needed
                    steamID3 = BitConverter.ToUInt32(byteSteamID64, 0);
                    textBoxSteamID3.Text = steamID3.ToString();

                    steamID64 = BitConverter.ToUInt64(byteSteamID64, 0);
                    textBoxSteamID64.Text = steamID64.ToString();
#if DEBUG
                    Console.WriteLine("Read: " + BitConverter.ToString(byteSteamID64));
                    Console.WriteLine("SteamID3: " + steamID3.ToString());
                    Console.WriteLine("SteamID64: " + steamID64.ToString());
#endif

                    // Misc
                    textBoxWorkingFile.Text = filePath;
                    textBoxWorkingFile.SelectionStart = textBoxWorkingFile.TextLength;
                    toolStripStatusLabel1.Text = "Read from " + Path.GetFileName(filePath) + ": " + BitConverter.ToString(byteSteamID64);
                    lastStatus = toolStripStatusLabel1.Text;

                    // Check if a new ID is already written, and if so, enable the button
                    if (String.IsNullOrWhiteSpace(textBoxSteamID64_New.Text) == false && String.IsNullOrWhiteSpace(filePath) == false && textBoxSteamID64_New.Text != textBoxSteamID64.Text)
                    {
                        buttonUpdate.Enabled = true;
                    }
                    else
                    {
                        buttonUpdate.Enabled = false;
                    }
                } catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static byte[] ReadBinary(string filename)
        {
            if (!File.Exists(filename))
            {
                return null;
            }
            var fs = new FileStream(filename, FileMode.Open);
            var buffer = new byte[(int)fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();
            return buffer;
        }

19 View Source File : KeyUtil.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public byte[] FindKey(string gamePath)
        {
            var gameExe = Path.Combine(gamePath, ExecutableName);

            const string validHash = "DEA375EF1E6EF2223A1221C2C575C47BF17EFA5E";
            byte[] key = null;

            var fs = new FileStream(gameExe, FileMode.Open, FileAccess.Read);

            foreach (var u in SearchOffsets)
            {
                if (u <= fs.Length - 32)
                {
                    var tempKey = new byte[32];
                    fs.Seek(u, SeekOrigin.Begin);
                    fs.Read(tempKey, 0, 32);

                    var hash = BitConverter.ToString(SHA1.Create().ComputeHash(tempKey)).Replace("-", "");
                    if (hash == validHash)
                    {
                        key = tempKey;
                        break;
                    }
                }
            }

            fs.Close();

            return key;
        }

19 View Source File : Modules.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24

public static string GetChunk(string File, int ChunkNum, int TotalChunks, long FileSize)
            {
                try
                {
                    byte[] file_chunk = null;
                    long pos = ChunkNum * Config.ChunkSize;
                    using (FileStream fileStream = new FileStream(File, FileMode.Open))
                    {
                        fileStream.Position = pos;
                        if (TotalChunks == ChunkNum + 1)
                        {
                            file_chunk = new byte[FileSize - (ChunkNum * Config.ChunkSize)];
                            int chunk_size = file_chunk.Length;
                            fileStream.Read(file_chunk, 0, chunk_size);
                        }
                        else
                        {
                            file_chunk = new byte[Config.ChunkSize];
                            fileStream.Read(file_chunk, 0, Config.ChunkSize);
                        }
                    }
                    return Convert.ToBase64String(file_chunk);
                }
                catch
                {
                    return "Error reading file";
                }
            }

19 View Source File : Modules.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24

public static string GetChunk(string File, int ChunkNum, int TotalChunks, long FileSize)
            {
                try
                {
                    byte[] file_chunk = null;
                    long pos = ChunkNum * Config.ChunkSize;
                    using (FileStream fileStream = new FileStream(File, FileMode.Open))
                    {
                        fileStream.Position = pos;
                        if (TotalChunks == ChunkNum + 1)
                        {
                            file_chunk = new byte[FileSize - (ChunkNum * Config.ChunkSize)];
                            int chunk_size = file_chunk.Length;
                            fileStream.Read(file_chunk, 0, chunk_size);
                        }
                        else
                        {
                            file_chunk = new byte[Config.ChunkSize];
                            fileStream.Read(file_chunk, 0, Config.ChunkSize);
                        }
                    }
                    return Convert.ToBase64String(file_chunk);
                }
                catch
                {
                    return "Error reading file";
                }
            }

See More Examples