C#读取网站txt文件

Since this question and my previous answer is fairly old now, a more modern answer would be to use HttpClient from System.Net.Http

using System.Net.Http;

namespace ConsoleApp2
{
    class Program
    {
        async static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            string result = await client.GetStringAsync("https://example.com/test.txt");
        }
    }
}

If not within an async function, then:

string result = client.GetStringAsync("https://example.com/test.txt").Result;

原文链接:https://stackoverflow.com/questions/12240857/how-to-get-content-from-file-from-this-url

sta/websocket-sharp库winform客户端简单例子2

Websocket C# Example

Here is an example of a web socket client application written in C#. It uses the websocket-sharp library.

This example will show you how to set up a web socket client to access the JNIOR to toggle an output. The screenshot below was taken when the JNIOR being accessed had a harness connecting the relay outputs to the digital inputs.

Form1.cs

using com.integ.websocket;
using System;
using System.Windows.Forms;

namespace WebSocketExample
{
    public partial class Form1 : Form
    {
        private JniorWebSocket _jniorWebsocket;



        public Form1()
        {
            InitializeComponent();
        }



        // Callback from the jnior web socket object.  here we will log the message that was 
        // received straigh to the log window
        private void _jniorWebsocket_Log(object sender, LogEventArgs args)
        {
            LogToWindow(args.Message);
        }



        // connected callback from the jnior web socket object
        private void _jniorWebsocket_Connected(object sender, EventArgs e)
        {
            LogToWindow("Connected\r\n");
            SetMenu(true);
        }



        // disconnected callback from the jnior web socket object
        private void _jniorWebsocket_Disconnected(object sender, EventArgs e)
        {
            LogToWindow("Disconnected\r\n");
            SetMenu(false);
        }



        private void SetMenu(bool connected)
        {
            Invoke((MethodInvoker)delegate
            {
                connectToolStripMenuItem.Enabled = !connected;
                closeOutput1ToolStripMenuItem.Enabled = connected;
            });
        }



        // our logging funciton
        private void LogToWindow(string text)
        {
            // make sure to invoke this on the main window thread
            Invoke((MethodInvoker)delegate
            {
                textBox1.AppendText(DateTime.Now.ToString("HH:mm:ss.fff") + "   " + text);
            });
        }



        // toggle menu item click handler
        private void toggleOutput1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // send a new toggle output object for channel 1
            _jniorWebsocket.Send(new ToggleOutput(1));
        }



        // connect menu item click handler
        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // create the jnior web socket object with the IP Address that we want to connect to
            _jniorWebsocket = new JniorWebSocket("10.0.0.122");

            // if we are connecting securely we need to specify to accept untrusted certificates
            _jniorWebsocket.AllowUnstrustedCertificate = true;

            // wireup some callbacks
            _jniorWebsocket.Log += _jniorWebsocket_Log;
            _jniorWebsocket.Connected += _jniorWebsocket_Connected;
            _jniorWebsocket.Disconnected += _jniorWebsocket_Disconnected;

            // connect!
            _jniorWebsocket.Connect();
        }

    }
}

JniorWebSocket.cs

using Newtonsoft.Json.Linq;
using SuperSocket.ClientEngine;
using System;
using WebSocket4Net;

namespace com.integ.websocket
{
    class JniorWebSocket
    {
        public delegate void LogEventHandler(object sender, LogEventArgs args);
        public event LogEventHandler Log;
        public event EventHandler Connected;
        public event EventHandler Disconnected;

        private WebSocket _websocket;
        private string _uri;

        public JniorWebSocket(string host) : this(host, 0) { }


        public JniorWebSocket(string host, int port)
        {
            _uri = "ws://" + host;
            if (0 != port) _uri += ":" + port;

            _websocket = new WebSocket(_uri);
            _websocket.Opened += new EventHandler(websocket_Opened);
            _websocket.Error += Websocket_Error;
            _websocket.Closed += websocket_Closed;
            _websocket.MessageReceived += Websocket_MessageReceived;
        }



        public bool AllowUnstrustedCertificate
        {
            get
            {
                return _websocket.AllowUnstrustedCertificate;
            }
            set
            {
                _websocket.AllowUnstrustedCertificate = value;
            }
        }



        public void Connect()
        {
            Log?.Invoke(this, new LogEventArgs("Connect to " + _uri + "\r\n"));
            _websocket.Open();
        }



        public void Send(JObject json)
        {
            try
            {
                Log?.Invoke(this, new LogEventArgs("SEND -> " + json.ToString(Newtonsoft.Json.Formatting.None) + "\r\n"));
                _websocket.Send(json.ToString());
            }
            catch (Exception ex)
            {
                Log?.Invoke(this, new LogEventArgs("\r\n" + ex.ToString() + "\r\n\r\n"));
            }
        }



        private void Websocket_Error(object sender, ErrorEventArgs e)
        {
            Log?.Invoke(this, new LogEventArgs("\r\n" + e.Exception.ToString() + "\r\n\r\n"));
        }



        private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            var json = JObject.Parse(e.Message);

            Log?.Invoke(this, new LogEventArgs("RECV <- " + json.ToString(Newtonsoft.Json.Formatting.None) + "\r\n"));

            var message = json["Message"].ToString();
            if ("Error".Equals(message)) HandleErrorMessage(json);
        }



        private void HandleErrorMessage(JObject json)
        {
            var text = json["Text"].ToString();
            if ("401 Unauthorized".Equals(text))
            {
                var nonce = json["Nonce"].ToString();
                var username = "jnior";
                var password = "jnior";

                var login = new Login(username, password, nonce);
                Send(login);
            }
        }



        private void websocket_Opened(object sender, EventArgs e)
        {
            Connected?.Invoke(this, EventArgs.Empty);
            Send(JniorMessage.Empty);
        }



        private void websocket_Closed(object sender, EventArgs e)
        {
            Disconnected?.Invoke(this, EventArgs.Empty);
        }

    }
}

JniorMessage.cs

using Newtonsoft.Json.Linq;

namespace com.integ.websocket.messages
{
    // extends the JObject Newtonsonft JSON object
    public class JniorMessage : JObject
    {
        public static JniorMessage Empty;



        // creates an empty object that we use when the connection is made.  when the jnior 
        // receives this it will either send us a monitor packet or an unauthorized message
        static JniorMessage()
        {
            Empty = new JniorMessage();
            Empty["Message"] = "";
        }
    }
}

LogEventArgs.cs

namespace com.integ.websocket
{
    public class LogEventArgs
    {
        public string Message { get; set; }



        public LogEventArgs(string message)
        {
            Message = message;
        }
    }
}

UnauthorizedEventArgs.cs

namespace com.integ.websocket
{
    public class UnauthorizedEventArgs
    {
        // The nonce that is used to build the auth digest
        public string Nonce { get; set; }
 
 
 
        public UnauthorizedEventArgs(string nonce)
        {
            Nonce = nonce;
        }
    }
}

原文链接:http://home.integpg.com/janossdk/websocket-csharp-example.html

sta/websocket-sharp库winform客户端简单例子1

Create a winform Application:

image

Add below code:

 private WebSocket client;
        const string host = “wss://echo.websocket.org”;

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new WebSocket(host);

            client.OnOpen += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Connected to {0} successfully “, host));
            client.OnError += (ss, ee) =>
               listBox1.Items.Add(”     Error: “ + ee.Message);
            client.OnMessage += (ss, ee) =>
               listBox1.Items.Add(“Echo: “ + ee.Data);
            client.OnClose += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Disconnected with {0}”, host));
        }

Add below button click event handler:

private void SendButton_Click(object sender, EventArgs e)
        {
            var content = inputBox.Text;
            if(!string.IsNullOrEmpty(content))
                client.Send(content);
        }

        private void ConnectButton_Click(object sender, EventArgs e)
        {
            client.Connect();
        }

        private void DisconnectButton_Click(object sender, EventArgs e)
        {
            client.Close();
        }

That is it! Run your app and enjoy!

原文链接: https://xinyustudio.wordpress.com/2015/07/23/c-websocket-programming-the-simplest-example/

C#读写app.config示例

using System;  
using System.Configuration;  
  
namespace ConsoleApplication1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ReadAllSettings();  
            ReadSetting("Setting1");  
            ReadSetting("NotValid");  
            AddUpdateAppSettings("NewSetting", "May 7, 2014");  
            AddUpdateAppSettings("Setting1", "May 8, 2014");  
            ReadAllSettings();  
        }  
  
        static void ReadAllSettings()  
        {  
            try  
            {  
                var appSettings = ConfigurationManager.AppSettings;  
  
                if (appSettings.Count == 0)  
                {  
                    Console.WriteLine("AppSettings is empty.");  
                }  
                else  
                {  
                    foreach (var key in appSettings.AllKeys)  
                    {  
                        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);  
                    }  
                }  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error reading app settings");  
            }  
        }  
  
        static void ReadSetting(string key)  
        {  
            try  
            {  
                var appSettings = ConfigurationManager.AppSettings;  
                string result = appSettings[key] ?? "Not Found";  
                Console.WriteLine(result);  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error reading app settings");  
            }  
        }  
  
        static void AddUpdateAppSettings(string key, string value)  
        {  
            try  
            {  
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
                var settings = configFile.AppSettings.Settings;  
                if (settings[key] == null)  
                {  
                    settings.Add(key, value);  
                }  
                else  
                {  
                    settings[key].Value = value;  
                }  
                configFile.Save(ConfigurationSaveMode.Modified);  
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);  
            }  
            catch (ConfigurationErrorsException)  
            {  
                Console.WriteLine("Error writing app settings");  
            }  
        }  
    }  
}

原文链接: https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings

C#控制台程序获取密码输入并以*显示

Console.Write(“\b \b”); will delete the asterisk character from the screen, but you do not have any code within your else block that removes the previously entered character from your pass string variable.

Here’s the relevant working code that should do what you require:

string pass = "";
do
{
    ConsoleKeyInfo key = Console.ReadKey(true);
    // Backspace Should Not Work
    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
    {
        pass += key.KeyChar;
        Console.Write("*");
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
        {
            pass = pass.Substring(0, (pass.Length - 1));
            Console.Write("\b \b");
        }
        else if(key.Key == ConsoleKey.Enter)
        {
            break;
        }
    }
} while (true);

原文链接: https://stackoverflow.com/questions/3404421/password-masking-console-application