在 C# 中创建一个固定宽度的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/86413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a fixed width file in C#
提问by Brian G
What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this?
在 C# 中创建固定宽度文件的最佳方法是什么。我有一堆字段的长度要写出来。说 20,80.10,2 等都左对齐。是否有捷径可寻?
采纳答案by Wheelie
You can use string.Format to easily pad a value with spaces e.g.
您可以使用 string.Format 轻松地用空格填充值,例如
string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300);
string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300);
// 'a' will be equal to "| 1| 20| 300|"
// 'b' will be equal to "|1 |20 |300 |"
回答by artur02
Can't you use standard text file? You can read back data line by line.
你不能使用标准的文本文件吗?您可以逐行读回数据。
回答by Chris Ballance
回答by viggity
Try using myString.PadRight(totalLengthForField, ' ')
尝试使用 myString.PadRight(totalLengthForField, ' ')
回答by Scott Dorman
You can use a StreamWriter and in the Write(string) call use String.Format() to create a string that is the correct width for the given field.
您可以使用 StreamWriter 并在 Write(string) 调用中使用 String.Format() 为给定字段创建一个正确宽度的字符串。
回答by Andrew Burgess
Use the .PadRight function (for left aligned data) of the String class. So:
使用 String 类的 .PadRight 函数(用于左对齐数据)。所以:
handle.WriteLine(s20.PadRight(20));
handle.WriteLine(s80.PadRight(80));
handle.WriteLine(s10.PadRight(10));
handle.WriteLine(s2.PadRight(2));
回答by Tobi
You mean you want to pad all numbers on the right with spaces?
你的意思是你想用空格填充右边的所有数字?
If so, String.PadRightor String.Formatshould get you on track.
如果是这样,String.PadRight或String.Format应该会让你走上正轨。
回答by davenpcj
You could use ASCIIEncoding.UTF8.GetBytes(text) to convert it to a byte array. Then write the byte arrays out to the file as a fixed-size record.
您可以使用 ASCIIEncoding.UTF8.GetBytes(text) 将其转换为字节数组。然后将字节数组作为固定大小的记录写入文件。
UTF8 varies in the number of bytes required to represent some characters, UTF16 is a little more predictable, 2 bytes per character.
UTF8 在表示某些字符所需的字节数方面有所不同,UTF16 的可预测性更强一些,每个字符 2 个字节。
回答by Yitzchok
You can use http://www.filehelpers.com/
回答by Leandro Oliveira
Try FileHelpers: www.filehelpers.com
试试 FileHelpers:www.filehelpers.com
Here's an example: http://www.filehelpers.com/quick_start_fixed.html