目前分類:C# (23)
- Jan 11 Thu 2018 10:17
[Reg][C#] 關於登錄檔概念、C#程式操作
- Jan 11 Thu 2018 09:12
[程式][C#] 目錄依次遞減刪除檔案與資料夾
在安裝程式中,有時會遇到它的設計是:
移除的檔案 若所在的資料夾 有其他檔案或資料夾,就只把安裝的檔案刪除,仍留下其他(可能是使用者自己放進去)的檔案/資料夾。
以下是用程式實作的範例:
- Jan 09 Tue 2018 15:26
[程式][C#] 測試連線到指定Server (HttpWebRequest)
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; } }
- Dec 21 Thu 2017 15:46
[程式][C#] 取登錄檔(Registry)的值
舉例:
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)
- Dec 21 Thu 2017 14:33
[程式][C#] 寫入文字檔的方法(含新增文字檔)
目前知道的有:
- 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
- Dec 21 Thu 2017 14:13
[程式][C#] 如何..建立資料夾+檔案?
- Dec 21 Thu 2017 14:00
[程式][C#] 如何取得當前使用者的資料夾(目錄)?
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)
- Dec 18 Mon 2017 11:41
[程式][C#] 如何開啟使用者的預設瀏覽器?
- Dec 13 Wed 2017 11:43
[程式][C#] 如何 確保/得知 WebBrowser(控制項) 已完成載入頁面?
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?
- Dec 13 Wed 2017 11:38
[程式][C#] 如何檢查字串為合法的HTTP URL?
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?
- Dec 13 Wed 2017 11:33
[程式][C#] 不區分大小寫 比對字串
string title = "STRING"; bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;
參考:Case insensitive 'Contains(string)'
- Sep 30 Sat 2017 10:21
[程式][C#][WinForm][Web] 如何用post上傳檔案,含參數?
程式碼範例:
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); }
請依所需自行調整。
- Sep 30 Sat 2017 10:14
[程式][C#] 如何將 位元組陣列 轉成 字串?
一行解決:
string str = System.Text.Encoding.Default.GetString(result);
- Aug 30 Wed 2017 09:19
[程式][C#] 如何以程式將資料夾設為共享?
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
- Mar 18 Sat 2017 21:36
[程式][C#][LINQ] 如何過濾array取得想要的資料呢?
C# 在 .NET 3.0 後,可以使用 LINQ 查詢語言,直接對 array 中的值 進行篩選。 寫起來類似 SQL 語言,只是上下順序顛倒過來而已。
相反地,Java 就沒有像 C# 加那麼多東西。
範例:
- Mar 18 Sat 2017 21:29
[程式][C#] 使用 KeyValuePair 或 DictionaryEntry 呢?
在 Java 的 HashMap 使用 "entryset",那在 C# 呢?
C# 的 Dictionary 可用 KeyValuePair 或 DictionaryEntry。
但是... 用哪一個好呢?
- Mar 18 Sat 2017 21:12
[程式][C#] 已存入Dictionary的值怎麼取呢?
以自己為例,用 Java 的 HashMap 用習慣了,對應到 C# 的 Dictionary 一直不知道怎麼取值。
C# 的語法比較特別,取陣列裡的值,'[' ']' 除了代入數值外,大部分的 API 支援 在裡頭填字串。
範例:
- Mar 14 Tue 2017 18:00
[程式][C#] 資料型別
- Mar 09 Thu 2017 15:52
[程式][C#] 如何隨機產生整數?
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
- Mar 09 Thu 2017 15:34
[程式][C#] 怎麼寫傳遞多個參數的function?
呼叫/使用:
int x = 1, y = 2, z = 3 ; F( x ); F( x, y ); F( x, y, z );
定義:
public static void F( params int[] values ) { // ... }