顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

Get 301 Moved Location

Processing HTTP 301 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(links[i]);
myHttpWebRequest.AllowAutoRedirect = false;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine(myHttpWebResponse.GetResponseHeader("Location"));
myHttpWebResponse.Close();

Verify Http URI public static bool IsValidHttpUri(string uriString)
{
    Uri test = null;
    return Uri.TryCreate(uriString, UriKind.Absolute, out test) && test.Scheme == "http";
}

.net - Using WebClient in C# is there a way to get the URL of a site after being redirected? - Stack Overflow
c# - RegEx to detect syntactically correct URL - Stack Overflow

sorting by file size

DirectoryInfo dir = new DirectoryInfo("K:\\VGD-103");
FileInfo[] files= dir.GetFiles("*.rar");

Array.Sort(files, (f1, f2) => f1.Length.CompareTo(f2.Length));    //排序檔案大小

foreach (FileInfo f in files)
    Console.WriteLine("{0}\t{1}",f.Name,f.Length/1024);

system.io - How to sort an array of FileInfo[] C# - Stack Overflow

設定C# Console字型顏色

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("ABC");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("ABC");

System.Text.RegularExpressions.Regex.Split

using System.IO;

StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + "\\note.txt");
List<string> listLines = new List<string>();
listLines.AddRange(System.Text.RegularExpressions.Regex.Split(sr.ReadToEnd(), "\r\n"));
sr.Dispose();

建立捷徑

static void urlShortcutToDesktop(string linkName, string linkUrl)
{
    using (StreamWriter writer = new StreamWriter(rootPath + linkName + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
        writer.Flush();
    }
}

StringSplitOptions.RemoveEmptyEntries

string str = "aaa,bbb,ccc,,ddd";
string[] strAry = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strAry.Length; i++)
    Console.WriteLine(strAry[i]);

String.Split 方法 (Char[], StringSplitOptions) (System)
用 split() 分割字串 : 文章 : 格子樑 | 艾倫 郭 | AllenKuo.com

WebClient download HTML source code

using System;
using System.IO;
using System.Net;
using System.Text;

string source;
using (WebClient wc=new WebClient())
{
    //方法1:使用串流讀取
    StreamReader sr=new StreamReader(wc.OpenRead("http://tw.yahoo.com"),Encoding.UTF8);
    source=sr.ReadToEnd();
    sr.Close();
    sr.Dispose();
           
    //方法2:使用webclient.DownloadString()
    //source=wc.DownloadString("http://tw.yahoo.com");
}
Console.WriteLine(source);

C# Array.ForEach Method

string[] testAry = { "Apple","bbb", "Ben", "aaa" };
Array.Sort(testAry);
Array.ForEach(testAry, delegate(string str) { Console.WriteLine(str); });

HashCode x Random

Random Counter = new Random(Guid.NewGuid().GetHashCode());
[C#]不同的Random物件給予不同的亂數種子 - Level Up- 點部落

UTF8Encoding And BOM

//Write with BOM
File.WriteAllText(path, content,new UTF8Encoding(true));

//Write with no BOM
File.WriteAllText(path, content,new UTF8Encoding(false));

UTF8Encoding 建構函式 (Boolean) (System.Text)
KB-UTF8Encoding And BOM - 黑暗執行緒

Creating URL shortcut

private void urlShortcutToDesktop(string linkName, string linkUrl)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
        writer.Flush();
    }
}

C# - Creating URL shortcut to desktop

查詢硬碟剩餘空間(using WinAPI)

using System.Runtime.InteropServices;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
    out ulong lpFreeBytesAvailable,
    out ulong lpTotalNumberOfBytes,
    out ulong lpTotalNumberOfFreeBytes);

string drive = "D:\\";      // 要查詢剩餘空間的磁碟
ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;
bool success = GetDiskFreeSpaceEx(drive, out FreeBytesAvailable, out TotalNumberOfBytes, out TotalNumberOfFreeBytes);

if (!success)    throw new System.ComponentModel.Win32Exception();

double free_kilobytes = (double)(Int64)TotalNumberOfFreeBytes / 1024.0;
double free_megabytes = free_kilobytes / 1024.0;
double free_gigabytes = free_megabytes / 1024.0;

//取得Server IP
System.Net.IPAddress sever_ip = new System.Net.IPAddress(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].Address);
Response.Write(sever_ip.ToString() + " 剩餘 " + free_gigabytes.ToString("0.00") + " GB");

[C#]查詢硬碟剩餘空間(透過WinAPI) - .NET菜鳥自救會- 點部落
C# 如何取得本機(Server)的IP @ R~福氣拉! :: 隨意窩 Xuite日誌

C# 控制項拖曳

control.AllowDrop = True;    //記得一定要開,否則下面程式都不會跑
private void control_DragDrop(object sender, DragEventArgs e)
{
    string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
    foreach (string fileLoc in filePaths)
    {

    }
}
private void control_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Link;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

Drag and Drop Text Files from Windows Explorer to your Windows Form Application
Visual Basic 2005 – 如何拖放圖片 @ 章立民研究室
4.5托曳事件 - Happy VB開心農莊

C# Debug

using System.Diagnostics;
Debug.Print("xxx");
Debug.WriteLine("xxx");

Debug 方法 (System.Diagnostics)

ExecuteScalar回傳值

無資料的時候:cmdSQL.ExecuteScalar 傳回null
有資料但資料為null時:cmdSQL.ExecuteScalar 傳回DbNull.Value