想知道如果你有更好的建议,我已经想出了。写入文件和格式化行。需要的结果
我有要求以特定格式编写文本文件 每个字段必须从所述位置开始,并且必须用空格填充,直到下一个字段。
例子:
Field Position in the row
Name 1
Surname 20
Address 50
Country 90
DOB 120
MaritalStatus 160
下面是我的原型的尝试,有没有这样做的一个整洁的更好的办法? 需要在单元测试中测试行中的位置是否正确?
有什么建议吗?
class Program
{
static void Main(string[] args)
{
Customer customer=new Customer();
customer.Name = "Jo";
customer.Surname = "Bloggs";
customer.Address = " 1 NewYork Road";
customer.Country = "UK";
customer.DOB = "29/04/1990";
customer.MaritalStatus = "Married";
StringBuilder sb=new StringBuilder();
CreateHeader(customer,sb);
sb.AppendLine("");
CreateRow(customer, sb);
sb.AppendLine("");
IOExtensions.WriteToFile(sb.ToString(), "TestFile.txt");
}
private static void CreateHeader(Customer customer,StringBuilder sb)
{
/*
*
Field Position in the row
Name 1
Surname 20
Address 50
Country 90
DOB 120
MaritalStatus 160
*/
//First Field
sb.Append(FormatValue("Name", 19));
sb.Append(FormatValue("Surname", 29));
sb.Append(FormatValue("Address", 39));
sb.Append(FormatValue("Country", 29));
sb.Append(FormatValue("DOB", 39));
//Last field does not matter
sb.Append(FormatValue("MaritalStatus", 9));
}
private static void CreateRow(Customer customer, StringBuilder sb)
{
/*
*
Field Position in the row
Name 1
Surname 20
Address 50
Country 90
DOB 120
MaritalStatus 160
*/
//First Field
sb.Append(FormatValue(customer.Name, 19));
sb.Append(FormatValue(customer.Surname, 29));
sb.Append(FormatValue(customer.Address, 39));
sb.Append(FormatValue(customer.Country, 29));
sb.Append(FormatValue(customer.DOB, 39));
//Last field does not matter
sb.Append(FormatValue(customer.MaritalStatus, 19));
}
private static string FormatValue(string value, int maxLength)
{
//TODO ADD OTHER STUFF HERE
return value.PadRight(maxLength, ' ');
}
}
public static class IOExtensions
{
public static void WriteToFile(string text, string path)
{
using (var fs = File.CreateText(path))
{
fs.Write(text);
}
}
}
public class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string DOB { get; set; }
public string MaritalStatus { get; set; }
}
}
这种问题可能更适合http://codereview.stackexchange.com – StriplingWarrior
你可以使用FileHelpers http://www.filehelpers.com/default.html – kd7