我是編程新手,但我喜歡它,並且我正在嘗試儘可能地學習。 我正在編寫一個小型應用程序,它有一個多行文本框(txtOutput),我在其中輸入我的評論。這些註釋/行然後以一串字符串傳輸。 然後,我調用一個類傳遞一些變量,並且還將數組全部打印到一個txt文件中。 雖然我可以從變量中獲取填充了數據的txt文件,但我無法將數組的內容獲取到txt文件中。我希望得到一些幫助。從爲txtOutput打印字符串數組到txt文件
文本陣列
public void button6_Click(object sender, EventArgs e)
{
string[] comments = txtOutput.Text.Split(' ');
陣列和其他變量到Class的轉移(其中我的代碼來創建和保存這些變量的內容和數組txt文件) 。另外兩個變量在文件上打印出來沒有問題。
WriteTextFile WTR = new WriteTextFile();
WTR.Save(temperatura, speedMotore, comments);
Class1的代碼(如果我做讓txt文件,並保存它。
class WriteTextFile
{
public void Save(int sendTem, int sendMot, string[] comments)
{
DateTime Now = DateTime.Now;
string dateTime = Now.ToString("F");
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Text File | *.txt";
if (sd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sd.FileName))
{
sw.Write("File diconfigurazione del programma Arduino Control " + "\r\n");
sw.Write("\r\n");
sw.Write(dateTime + "\r\n");
sw.Write("\r\n");
sw.Write("\r\n");
sw.Write("La temperatura impostata in PWM1 è: " + sendMot + "\r\n");
sw.Write("\r\n");
sw.Write("La velocità del motore impostata in PWM2 è: " + sendTem + "\r\n");
sw.Write("\r\n");
sw.Write(comments[1] + "\r\n");
sw.Dispose();
sw.Close();
}
}}}
我不知道如果我從爲txtOutput任何文本正確地傳送到「意見」陣。我想實現的是從TXT文件中打印出來的txtOutput逐行讀取這些行,而我只是收到一條消息,指出「索引超出範圍.......」
你的數組索引從零開始 - 我懷疑'評論[0]'而不是'評論[1 ]'可能會訣竅。 – Floris
您使用'sw.Write'並且每次添加字符串'「\ r \ n」'。使用'sw.WriteLine'代替它更容易和更清楚。你不必使用'sw.Dispose()'和'sw.Close()',因爲你已經把'sw'放入''using'塊(就像你必須的那樣)。你得到的「索引超出範圍」來自數組訪問'comments [1]'。檢查'comments.Length'。 ''[']'中的索引從零開始並以_minus one_結尾。 –