简体   繁体   English

写入文本文件C#

[英]Writing to a text file C#

I have the following values 我有以下值

A = 1, 
B = (NULL of 7 characters), 
C = denimRocks , 
D = Yes789, 
E = (NULL of 2 characters), 
F = ATR.

I want to write these to a line of a textfile with A starting at position 1 of the line. 我想写这些与一个出发在该行的第1位的直线的文本文件中。 B starting at position 2, C at position 8 and so on. B从位置2开始, C从位置8开始,依此类推。

I want to show blank spaces for the nulls. 我想为空值显示空白。 I tried using streamwriter but I cant get to acheive what I want to do. 我尝试使用Streamwriter,但无法实现自己想要的功能。

Help please. 请帮助。

Try like this: 尝试这样:

 string a=string.Empty;
    StreamWriter yourStream = null;
    protected void Page_Load(object sender, EventArgs e)
    {
            yourStream = File.CreateText("D:\\test1.txt"); // creating file
            a = String.Format("|{0,1}|{1,2}|{2,7}|......", "A", "B", "",......); //formatting text based on poeition
            yourStream.Write(a+"\r\n");                        
            yourStream.Close();
        }

string.Format and the composite formatting rules allow to align a string exactly as you wish: string.Format和复合格式设置规则允许完全按照您的意愿对齐字符串:

 string A = "1";
 string B = "";
 string C = "denimRocks";
 string D = "yes789"
 string E = "";
 string F = "ATR";

 string result = string.Format("{0}{1,7}{2,10}{3,6}{4,2}{5,3}", A,B,C,D,E,F);
 Console.WriteLine(result);

In this way you get every piece of information aligned exactly in the spaces reserved for them and writing to a file is just a matter to open the appropriate stream and write the resulting string 这样,您就可以将每条信息精确地对齐在为它们保留的空间中,并写入文件仅是打开适当的流并写入结果字符串的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM