Question

My client requirment has fixed length file records in the format of header, body and footer but in the footer they wants to have an empty space of 1966 lenght . I tried this using difffent butttons for header and footer and body but was unable to specify space at the end. this was my code .. space is not working in this while creating footer.

    FileStream fs = new FileStream(@"C:\Users\IT-Administrator\Desktop\ee.txt", FileMode.Open, FileAccess.ReadWrite);
    fs.Seek(0, SeekOrigin.End);


    StreamWriter sw = new StreamWriter(fs);
    sw.WriteLine(comboBox6.Text + textBox2.Text + textBox3.Text + textBox4.Text + **SPACE(1966)** );


    sw.Close();
    fs.Close();**strong text**
Était-ce utile?

La solution 2

You can do this by using the overload of WriteLine that accepts a format specifier.

If you want the last element to take a total of 1966 characters, you can write :

using(var sw=new StreamWriter(@"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
    sw.WriteLine("{0}{1}{2}{3,-1966}",comboBox6.Text ,textBox2.Text,
                                     textBox3.Text,textBox4.Text );
}

This way it's much easier to see what the actual string will look like. For example, you can see that you are actually joining all elements in one continuous string. Perhaps, what you wanted to do was to separate them by spaces, eg: "{0} {1} {3} {4,-1966}"

If you want the the last element to be followed by 1966 spaces:

using(var sw=new StreamWriter(@"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
    sw.WriteLine("{0}{1}{3}{4}{5,-1966}",comboBox6.Text ,textBox2.Text,
                                     textBox3.Text,textBox4.Text,' ');
}

In the above code, using makes sure the StreamWriter will close even if an exception occurs. The code also avoids creating both a StreamWriter and FileStream by creating the StreamWriter with a path argument

Autres conseils

Use String.PadRight() to pad the string.

Say for example the max string length was 2000 characters, you can do something like this:

string example = "Example";
string full_example = example.PadRight(2000);

This will take the length of the original string and pad it out with spaces until it reaches the desired width.

In your case if you wanted exactly 1966 spaces though you can do this:

string spaces = String.Empty.PadRight(1966);

If you want to create a string consisting of 1966 spaces, you can use the string constructor that takes a character and a number of times to repeat it: new String(' ', 1966).

If you want to pad strings out to a particular length, you can use PadRight or PadLeft as appropriate.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top