我使用以下代码写入项目根文件夹中的文件..
public class Service2 : IService2
{
public Boolean SaveInfo(String firstName, String lastName, DateTime dateOfBirth,
String email, String streetAddress, String suburb, String state, int postcode,
Job job)
{
string text = firstName + " " + lastName + " " + dateOfBirth + " " + email + " " + streetAddress + " " + suburb + " " + state + " " + postcode + " " + job;
String[] people = Regex.Split(text, " ");
using (System.IO.StreamWriter file = new System.IO.StreamWriter("Person.txt", true))
{
foreach (string c in people)
{
file.Write(c);
file.Close();
return true;
}
return false;
}
}
基本上它返回一个布尔值,取决于文件是否被写入...我实际上找不到写入文件的内容。它在执行时确实返回true - 我在WCF测试器中运行WCF服务并使用值来调用它以写入文件...但是当我从右侧的Solution explorer打开Person.txt文件时,没有任何东西得到写进去......
所以我的问题是,这是将文本行写入文本文件的最佳方式,如果是这样,我哪里出错?
此致
答案 0 :(得分:1)
尝试使用此代码
string text = firstName + " " + lastName + " " + dateOfBirth + " " + email + " " + streetAddress + " " + suburb + " " + state + " " + postcode + " " + job;
String[] people = text.Split(" ");
if (!File.Exists("Person.txt"))
{
// Create a file to write to.
File.WriteAllLines(path, people , Encoding.UTF8);
}
else
File.AppendAllText("Person.Text", people , Encoding.UTF8);
答案 1 :(得分:1)
public Boolean SaveInfo(String firstName, String lastName, DateTime dateOfBirth,
String email, String streetAddress, String suburb, String state, int postcode)
{
string text = firstName + " " + lastName + " " + dateOfBirth + " " + email + " " + streetAddress + " " + suburb + " " + state + " " + postcode + " ";
String[] people = Regex.Split(text, " ");
try
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter("Person.txt", true))
{
foreach (string c in people)
{
file.Write(c);
}
file.Close();
}
return true;
}
catch (Exception)
{
return false;
}
}
您在数组中的第一个字符串后关闭文件,但是在遍历数组中的每个字符串后必须关闭它。 对我而言,这是有效的,但我们可能需要看到你的函数调用
答案 2 :(得分:0)
试试这个
public Boolean SaveInfo(String firstName, String lastName, DateTime dateOfBirth,
String email, String streetAddress, String suburb, String state, int postcode,
Job job)
{
try{
string text = firstName + "\r\n" + lastName + "\r\n" + dateOfBirth + "\r\n" + email + "\r\n" + streetAddress + "\r\n" + suburb + "\r\n" + state + "\r\n" + postcode + "\r\n" + job;
using (System.IO.StreamWriter file = new System.IO.StreamWriter("Person.txt"))
{
file.WriteLine(text );
file.Close();
return true;
}
}
catch(Exception ex)
{
return false;
}
}
答案 3 :(得分:0)
老式的方式
using (FileStream fs = File.Create(yourFilePath))
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
fs.Write(info, 0, info.Length);
}