###### tags: `ProgrammingLanguage`
# C#
:::spoiler 排除重覆資料
Hashtable ht = new Hashtable();
if (!ht.Contains(_selstchf.Table.Rows[i]["rank"].ToString())) //排除重複資料
{
rankCount++;
ht.Add(_selstchf.Table.Rows[i]["rank"].ToString(), _selstchf.Table.Rows[i]["rank"].ToString());
}
:::
---
```
#region 分割PDF檔
if (format == "pdfDownload")
{
//string path = @"D:\Users\LIU\Source\Workspaces\FR_ReportServer\ReportNet\FastReportCore.MVC\wwwroot\temp";
//當前專案路徑
string prjPath = Directory.GetCurrentDirectory();
//搜尋wwwroot路徑
string dir = Directory.GetDirectories(prjPath, "wwwroot", SearchOption.TopDirectoryOnly)[0] + "\\temp";
//存放分割PDF資料夾路徑
string spilt_PDF_dir = Directory.GetDirectories(prjPath, "wwwroot", SearchOption.TopDirectoryOnly)[0] + "\\SpiltPDF";
//存放zip資料夾
string zip_dir = Directory.GetDirectories(prjPath, "wwwroot", SearchOption.TopDirectoryOnly)[0] + "\\zip";
if (!Directory.Exists(spilt_PDF_dir))
Directory.CreateDirectory(spilt_PDF_dir);
DirectoryInfo directoryInfo = new DirectoryInfo(dir);
string currentPDF = tempFile;
if (Directory.Exists(spilt_PDF_dir))
{
PdfReader reader = null;
string sourcePdfPath = dir + "\\" + currentPDF; //要分割的pdf檔
try
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourcePdfPath);
string outputPdfFolder = spilt_PDF_dir; //匯出路徑
reader = new PdfReader(sourcePdfPath);
if(reader.NumberOfPages > 0)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
//讀取PDF檔內容並擷取學號當檔案名稱
var pdfText = PdfTextExtractor.GetTextFromPage(reader, i, new LocationTextExtractionStrategy());
string strKey = "學 號:"; //Regex規則
int keyIndex = 0;
string str = "";
string stuno = "";
MatchCollection matches = Regex.Matches(pdfText, strKey);
foreach (Match m in matches)
keyIndex = m.Index + m.Length;
str = pdfText.Substring(keyIndex, 10).Trim();
string[] stunoArr = str.Split(' ');
stuno = stunoArr[0];
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage = null;
Document sourceDocument = null;
string outputPdfPath = outputPdfFolder + "\\" + stuno + ".pdf";
sourceDocument = new Document(reader.GetPageSizeWithRotation(i));
pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(outputPdfPath, FileMode.Create));
sourceDocument.Open();
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
sourceDocument.Close();
}
reader.Close();
//匯出zip檔
//存放分割PDF資料夾路徑
if(!Directory.Exists(zip_dir))
Directory.CreateDirectory(zip_dir);
string startPath = outputPdfFolder;
string zipPath = zip_dir + "\\" + strReport + "_" + g.ToString().Replace("-", "") + ".zip";
ZipFile.CreateFromDirectory(startPath, zipPath);
//匯出ZIP檔後刪除所有檔案
new PublicFunction().DeleteDirectoryFile(outputPdfFolder);
}
}
catch (Exception ex)
{
throw ex;
}
}
return File("/zip/" + strReport + "_" + g.ToString().Replace("-", "") + ".zip", "application/x-zip-compressed", strReport + "_" + g.ToString().Replace("-", "") + ".zip");
}
```
---
```
/// <summary>
/// Html轉PDF匯出
/// </summary>
/// <param name="html">html語法</param>
/// <param name="path">Temp.pdf路徑</param>
public static void HtmlToPdf(string html, string path)
{
//Function Definition
StringBuilder paramsBuilder = new StringBuilder();
//Build command
paramsBuilder.AppendFormat("\"-\" \"{0}\"", path);
//process to execute above command
using (Process process = new Process())
{
//path of wkhtmltopdf.exe file
string filepath = @"wkhtmltopdf.exe";
//specify path
process.StartInfo.FileName = filepath;
//set command by argument
process.StartInfo.Arguments = paramsBuilder.ToString();
//set credentials
Console.InputEncoding = Encoding.UTF8;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
//start process
process.Start();
using (var stream = process.StandardInput)
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(buffer, 0, buffer.Length);
stream.WriteLine();
}
process.Close();
}
Thread.Sleep(2000);
}
```
---
```
匯出txt
bResult = Encoding.Unicode.GetBytes(new PublicFunction().txtExport(sSql, program_no));
return File(bResult, "text/plain", program_no + guid.ToString() + ".txt");
```
---
:::spoiler 數字轉英文
public static string NumberToText(int number, bool isUK)
{
if (number == 0)
return "Zero";
string and = isUK ? "and " : ""; // deals with UK or US numbering
if (number == -2147483648)
return "Minus Two Billion One Hundred " + and +
"Forty Seven Million Four Hundred " + and + "Eighty Three Thousand " +
"Six Hundred " + and + "Forty Eight";
int[] num = new int[4];
int first = 0;
int u, h, t;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (number < 0)
{
sb.Append("Minus ");
number = -number;
}
string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
string[] words3 = { "Thousand ", "Million ", "Billion " };
num[0] = number % 1000; // units
num[1] = number / 1000;
num[2] = number / 1000000;
num[1] = num[1] - 1000 * num[2]; // thousands
num[3] = number / 1000000000; // billions
num[2] = num[2] - 1000 * num[3]; // millions
for (int i = 3; i > 0; i--)
{
if (num[i] != 0)
{
first = i;
break;
}
}
for (int i = first; i >= 0; i--)
{
if (num[i] == 0) continue;
u = num[i] % 10; // ones
t = num[i] / 10;
h = num[i] / 100; // hundreds
t = t - 10 * h; // tens
if (h > 0) sb.Append(words0[h] + "Hundred ");
if (u > 0 || t > 0)
{
if (h > 0 || i < first) sb.Append(and);
if (t == 0)
sb.Append(words0[u]);
else if (t == 1)
sb.Append(words1[u]);
else
sb.Append(words2[t - 2] + words0[u]);
}
if (i != 0) sb.Append(words3[i - 1]);
}
return sb.ToString().TrimEnd();
}
:::
---
MessageBoxButtons
```
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show("警告,超過該課程類別最多可選上科目數,是否可選課?(Y/N)", "警告", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
if (result == DialogResult.No)
return null;
```
:::spoiler 西元民國轉換
```
/// <summary>
/// 西元年轉民國年
/// </summary>
/// <param name="dateTime"></param>
/// <returns>民國年tw</returns>
public static string CE_TO_TW(string datetime)
{
DateTime dt = DateTime.Parse(datetime);
CultureInfo culture = new CultureInfo("zh-TW");
culture.DateTimeFormat.Calendar = new TaiwanCalendar();
return dt.ToString("yyy/MM/dd", culture);
}
/// <summary>
/// 民國年轉西元年
/// </summary>
/// <param name="dateTime"></param>
/// <returns>西元年CE</returns>
public static string TW_TO_CE(string datetime)
{
CultureInfo culture = new CultureInfo("zh-TW");
culture.DateTimeFormat.Calendar = new TaiwanCalendar();
return DateTime.Parse(datetime, culture).ToString();
}
```
:::
---
:::spoiler 委派範例
```
public delegate void NotifyDelegate(string message);
class Program
{
static void Main(string[] args)
{
NotifyDelegate notify = null;
// 綁定多個方法
notify += SendEmail;
notify += SendSMS;
notify += LogToConsole;
// 調用委派,執行所有綁定方法
notify?.Invoke("System alert!");
// 移除一個方法
notify -= SendSMS;
Console.WriteLine("\nAfter removing SendSMS:");
notify?.Invoke("System alert again!");
}
static void SendEmail(string message)
{
Console.WriteLine($"Email: {message}");
}
static void SendSMS(string message)
{
Console.WriteLine($"SMS: {message}");
}
static void LogToConsole(string message)
{
Console.WriteLine($"Console: {message}");
}
}
```
:::