目前分類:C# (23)

瀏覽方式: 標題列表 簡短摘要

好文暫存:C#綜合揭祕—通過修改登錄檔建立Windows自定義協議

原文(簡體):C#综合揭秘——通过修改注册表建立Windows自定义协议

 

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

在安裝程式中,有時會遇到它的設計是:
移除的檔案 若所在的資料夾 有其他檔案或資料夾,就只把安裝的檔案刪除,仍留下其他(可能是使用者自己放進去)的檔案/資料夾。
以下是用程式實作的範例:

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

public static bool IsConnectingServer()
{
    string serverAddress = Properties.Settings.Default.ServerAddress;
    try
    {
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create( serverAddress );
        request.Method = "HEAD";
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        return response.StatusCode == HttpStatusCode.OK;
    } catch ( Exception )
    {
        return false;
    }
}

來源:C# Check Remote Server

參考:
Check whether a server is online using an IP and Port

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

舉例:

using System;
using Microsoft.Win32;
// ...
string keyName = @"HKEY_CURRENT_USER\Software\Microsoft\..."  // 相當於目錄.
string manifestValue = (string) Microsoft.Win32.Registry.GetValue( keyName, "Manifest", null );  // 相當於檔案'Manifest'.

參考:Registry.GetValue 方法 (String, String, Object)

 

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

目前知道的有:

  • System.IO.StreamWriter
  • System.IO.File.WriteAllLines
  • System.IO.File.WriteAllText
  • System.IO.File.CreateText

System.IO.StreamWriter:

    // 使用'using' 自動做Flush()、Close()、Dispose(), 釋放tw資源.
    using ( StreamWriter tw = new StreamWriter( "test.txt", true ) )  // 'true':新建或附加.
    {
        tw.WriteLine( "The next line!" );
    }

    using ( StreamWriter tw = new StreamWriter( "test.txt", false ) )  // 'false',或沒填:新建或覆蓋.
    {
        tw.WriteLine( "The next line!" );
    }

參考:Create a .txt file if doesn't exist, and if it does append a new line

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

後來才知道,不存在的路徑+檔案,是無法一次建立的。(目前所知)

 

建立「資料夾」的方法(含一連串不存在的目錄):

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
if ( Environment.OSVersion.Version.Major >= 6 ) {  // 判斷是不是Vista以上.
    path = Directory.GetParent(path).ToString();
}

來源:How can I get the current user directory?

參考:Operating System Version (version number)
備份:(2017/12/21)

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

原來這麼簡單...

Process.Start(@"http://www.google.com");

參考:
URL redirect + VSTO

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
     //This line is so you only do the event once   
     if (e.Url != webBrowser1.Url) 
        return;

        //do you actual code        

}

參考:How to make WebBrowser wait till it loads fully?

 


文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

參考:How to check whether a string is a valid HTTP URL?

 


文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;

參考:Case insensitive 'Contains(string)'

 


文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

 

程式碼範例:

public class UploadFile
    {
        public UploadFile()
        {
            ContentType = "application/octet-stream";
        }
        public string Name { get; set; }
        public string Filename { get; set; }
        public string ContentType { get; set; }
        public Stream Stream { get; set; }
    }
public byte[] UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
    {
        var request = WebRequest.Create(address);
        request.Method = "POST";
        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        boundary = "--" + boundary;

        using (var requestStream = request.GetRequestStream())
        {
            // Write the values
            foreach (string name in values.Keys)
            {
                var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.UTF8.GetBytes(values[name] + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            // Write the files
            foreach (var file in files)
            {
                var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);
                buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", file.ContentType, Environment.NewLine));
                requestStream.Write(buffer, 0, buffer.Length);
                file.Stream.CopyTo(requestStream);
                buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
                requestStream.Write(buffer, 0, buffer.Length);
            }

            var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
            requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
        }

        using (var response = request.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var stream = new MemoryStream())
        {
            responseStream.CopyTo(stream);
            return stream.ToArray();
        }
    }
using (var stream1 = File.Open("test.txt", FileMode.Open))
    using (var stream2 = File.Open("test.xml", FileMode.Open))
    using (var stream3 = File.Open("test.pdf", FileMode.Open))
    {
        var files = new[] 
        {
            new UploadFile
            {
                Name = "file",
                Filename = "test.txt",
                ContentType = "text/plain",
                Stream = stream1
            },
            new UploadFile
            {
                Name = "file",
                Filename = "test.xml",
                ContentType = "text/xml",
                Stream = stream2
            },
            new UploadFile
            {
                Name = "file",
                Filename = "test.pdf",
                ContentType = "application/pdf",
                Stream = stream3
            }
        };

        var values = new NameValueCollection
        {
            { "key1", "value1" },
            { "key2", "value2" },
            { "key3", "value3" },
        };

        byte[] result = UploadFiles("http://localhost:1234/upload", files, values);
    }

請依所需自行調整。

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

一行解決:

string str = System.Text.Encoding.Default.GetString(result);

 

參考:How convert byte array to string

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

1. 首先:要將「System.Management」加入參考。

2. 程式碼:

ManagementClass mClass = new ManagementClass( "Win32_Share" );
ManagementBaseObject mBaseObj_in = mClass.GetMethodParameters( "Create" );

mBaseObj_in["Path"] = installDirInfo.FullName ;  // 資料夾位置.
mBaseObj_in["Type"] = 0x0;  // 共用類型.

ManagementBaseObject mBaseOjb_out = mClass.InvokeMethod( "Create", mBaseObj_in, null );
if ( (uint)(mBaseOjb_out.Properties["ReturnValue"].Value) != 0)
{
    Console.WriteLine( "無法共享資料夾: " + mBaseOjb_out.Properties["ReturnValue"].Value );
}

/// ReturnValue:
///   0 – Success
///   2 – Access denied
///   8 – Unknown failure
///   9 – Invalid name
///  10 – Invalid level
///  21 – Invalid parameter
///  22 – Duplicate share
///  23 – Redirected path
///  24 – Unknown device or directory
///  25 – Net name not found

 

文章標籤

Robert 發表在 痞客邦 留言(1) 人氣()

C# 在 .NET 3.0 後,可以使用 LINQ 查詢語言,直接對 array 中的值 進行篩選。  寫起來類似 SQL 語言,只是上下順序顛倒過來而已。

相反地,Java 就沒有像 C# 加那麼多東西。

範例:

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

在 Java 的 HashMap 使用 "entryset",那在 C# 呢?

C# 的 Dictionary 可用 KeyValuePair 或 DictionaryEntry。

但是... 用哪一個好呢?

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

以自己為例,用 Java 的 HashMap 用習慣了,對應到 C# 的 Dictionary 一直不知道怎麼取值。

C# 的語法比較特別,取陣列裡的值,'[' ']' 除了代入數值外,大部分的 API 支援 在裡頭填字串。

範例:

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

範圍值:

  • long
    –9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807  // 整數.

 

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

 

Random rnd = new Random();
int month = rnd.Next(1, 13);  // 1 <= month < 13
int dice = rnd.Next(1, 7);    // 1 <= dice < 7
int card = rnd.Next(52);      // 0 <= card < 52

 

參考:How do I generate a random int number in C#?

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

呼叫/使用:

int x = 1, y = 2, z = 3 ;
F( x );
F( x, y );
F( x, y, z );

定義:

public static void F( params int[] values )
{
  // ...
}

參考:Pass multiple optional parameters to a C# function

文章標籤

Robert 發表在 痞客邦 留言(0) 人氣()

1 2