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

星期三, 1月 10, 2007

FILE的IO與Encoding

常用的IO class StreamReader就可以設定Encoding
StreamReader sr = new StreamReader("dic/wordlist_utf8.txt", Encoding.UTF8)

至於要把程式內的utf8 string轉成其它Encoding,以下是msdn的示範
string unicodeString = "This string contains the unicode character Pi(\u03a0)喔 是這樣嗎";

// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;

// Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString);

// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiString = new string(asciiChars);

// Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString);
Console.WriteLine("Ascii converted string: {0}", asciiString);
簡單的說,就是利用Encoding.Convert轉成不同encoding的byte[],然後再把byte[]轉成char[]或是string。

星期四, 12月 28, 2006

Visual Studio 2003自動加上的[STAThread] Tag

這是描述程式是哪種Thread型態:
  • Single-threaded Apartment[STA]

  • Multi-threaded Apartment[MTA]
稍微測試了一下,Visual Studio 2005在開新的C#專案時,並不會自動在Class宣告上加上這行[STAThread];所以應該是Visual Studio 2003才會這樣做。
至於詳細的差別,就要講到Single-thread與Multi-thread和COM的關係了。
When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

Windows Forms is not supported within a MTA or free threaded apartment.Applications using Windows Forms should always declare the apartment style they're using, as some other component could initialize the apartment state of thread improperly.