我需要使用StreamWriter
到寫入/存儲用戶正在輸入的信息。我已經得到了以下代碼的工作。C#StreamWriter不能隱式地將類型轉換爲字符串到SYSTEMS.IO
我現在需要讓它用用戶的名字寫一個文件,並將信息存儲在那裏。
隱藏展開復制代碼
case 2: //enter new user
//Enter new user information and add them to file
Console.Write("Please Enter the number of users you wish to log: ");
iUserNumber = Convert.ToInt32(Console.ReadLine());
//open file for writing, in APPEND mode
using (StreamWriter sw = new StreamWriter("NewUser" +sName,".txt", true))
{
//loop for each user
for (iCount = 1; iCount <= iUserNumber; iCount++)
{
// enter details
Console.Write("Please Enter your Name" + iCount + ": ");
sName = Console.ReadLine();
Console.Write("Please Enter the Name of your School: ");
sSchoolName = Console.ReadLine();
Console.WriteLine();
Console.Write("Please Enter the Name of your Class: ");
sClassName = Console.ReadLine();
// write to file
sw.WriteLine(sName);
Console.WriteLine();
sw.WriteLine(sSchoolName);
Console.WriteLine();
sw.WriteLine(sClassName);
Console.WriteLine("User data entered: ");
}
}
我似乎無法得到這個工作,並保持未來與這些錯誤:
參數1:無法從「字符串」轉換爲 'System.IO.Stream' FUNCOCO2
未分配的局部變量 'SNAME' FUNCOCO2的錯誤CS0165使用
錯誤CS1503參數2:無法從「字符串」轉換爲 「System.Text.Encoding」
我不知道如何解決這個問題。
我改成了這樣:
case 2: //enter new user
//Enter new user information and add them to file
Console.Write("Please Enter the number of users you wish to log: ");
iUserNumber = Convert.ToInt32(Console.ReadLine());
//enter first name
Console.WriteLine("Please enter your first Name: ");
sFirstName = Convert.ToString(Console.ReadLine());
//open file for writing, in APPEND mode
using (StreamWriter sw = new StreamWriter(sName))
{
//loop for each user
for (iCount = 1; iCount <= iUserNumber; iCount++)
{
// enter details
Console.Write("Please Enter your Name" + iCount + ": ");
sLastName = Console.ReadLine();
Console.Write("Please Enter the Name of your School: ");
sSchoolName = Console.ReadLine();
Console.WriteLine();
Console.Write("Please Enter the Name of your Class: ");
sClassName = Console.ReadLine();
// write to file
sw.WriteLine(sName);
Console.WriteLine();
sw.WriteLine(sSchoolName);
Console.WriteLine();
sw.WriteLine(sClassName);
Console.WriteLine("User data entered: ");
}
}
這似乎沒有任何工作。
'這似乎並沒有工作either.' <=請還包括錯誤消息就像你與你的第一次嘗試做。 – Igor
聽起來好像你想爲每個用戶創建一個新文件,但是你只打開一次文件 - 在循環之外。在你原來的「嘗試」中,你也錯誤地在'new StreamWriter(「NewUser」+ sName,「。txt」,true)'中使用了逗號而不是字符串連接。由於構造函數沒有這樣的重載,所以會出現一些令人困惑的錯誤。 – Luaan