在C#VS2012中写入文件
本文关键字:文件 C#VS2012 | 更新日期: 2023-09-27 18:29:15
我正在使用以下代码写入项目根文件夹中的文件。。
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服务,并用值调用它以写入文件。。。然而,当我从右侧的解决方案资源管理器打开Person.txt文件时,没有任何内容被写入其中…
所以我的问题是,这是将文本行写入文本文件的最佳方式吗?如果是,我哪里出了问题?
问候
尝试使用此代码
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);
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;
}
}
您在数组中的第一个字符串之后关闭文件,但必须在循环遍历数组中的每个字符串之后关闭它。对我来说,它正在工作,但我们可能需要看到您的函数调用
尝试这个
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;
}
}
一种老式的
using (FileStream fs = File.Create(yourFilePath))
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
fs.Write(info, 0, info.Length);
}