[英]Converting a textbox's text into a string to be used as a byte
好的,所以我想在c#表單上有幾個文本框,然后單擊某個按鈕時,它將在每個文本框中輸入文本,並將其轉換為要寫入文件的字節。 我知道如何做,但要取文本框的文本並將其變成一個字節。 有人可以幫忙嗎? 並且文本框文本將已經是十六進制形式,因此不必進行轉換。
您可以將字節寫為1和0到文本文件。
下面的示例假定您有一個名為textbox1的文本框,一個名為buttonRecord_Click的按鈕單擊事件,並且在代碼頂部(使用System.IO;)包括了對System.IO命名空間的引用。 用實際路徑替換“ PathOfYourTextFile.txt”。
private void buttonRecordBytes_Click(object sender, EventArgs e)
{
// Break if textbox1 is empty.
if (string.IsNullOrEmpty(textbox1.Text))
return;
// Variables:
int charCount = textbox1.Text.Length;
byte[] bytes = new byte[charCount];
string[] byteStrings = new string[charCount];
// StreamWriter will write the bytes to the text file.
StreamWriter sw = new StreamWriter("PathOfYourTextFile.txt", true);
// Record each character byte in textfile.
int i = 0;
foreach (char c in textbox1.Text)
{
// ASCII:
try
{
bytes[i] = Convert.ToByte(c);
byteStrings[i] = Convert.ToString(bytes[i], 2).PadLeft(8, '0');
}
// UTF8:
catch
{
bytes[i] = Encoding.UTF8.GetBytes(c.ToString().ToCharArray())[i];
byteStrings[i] = Convert.ToString(bytes[i], 2).PadLeft(24, '0');
}
// Append character and bit info to textfile.
sw.WriteLine("Character \"" + c.ToString() + "\" bits as ones and zeros: " +
byteStrings[i]);
ListViewItem lvi = new ListViewItem(i.ToString());
lvi.SubItems.Add(c.ToString());
lvi.SubItems.Add(byteStrings[i]);
listviewBytes.Items.Add(lvi);
i++;
}
sw.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.