Solved

Write multiple lines to txt file and start from specific postion on line

Posted on 2014-12-31
15
158 Views
Last Modified: 2015-01-04
I am writing a specific type of file from C# program and am trying to figure out how to acchomplish what I need.

What I need is the following -

There are multiple text boxes to enter data into such as firstname,middlename,lastname, ssn

I am looking to create a text file from this data which would have to be very specific for example.

I would create the text file and on the first line I would have"02C" then immediate following would have the first name then the middle name would start from the 20th position on the same line from the begining (which is where i cannot figure out some of it.)

then i would want it to create a second line in the text file that would show "03ABW" then immediately have the ssn

So the file in end would look like the following

"02CBOB             SMITH"
"03ABW123456789"

Notice there are 20 positions from the 1st to where "S" starts in Smith
0
Comment
Question by:desiredforsome
  • 8
  • 6
15 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 40525907
Not saying that what you want cannot be accomplished as you could use tab delimiters.  But using tab delimiters presents a problem when a person tries to read the file as opposed to a parser (or program).  Is there any reason why you would not want to use Xml or a comma-delimiter?

-saige-
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40525910
Hi desiredforsome;

Using String.Format will do what you want.

// Test Data
String begining = "02C";
String firstName = "BOB";
String lastName = "SMITH";
String begining2 = "03ABW";
String ssn = "123456789";

string output = String.Format("{0}{1,-17}{2}\n{3}{4}", begining, firstName, lastName, begining2, ssn);

Open in new window

0
 

Author Comment

by:desiredforsome
ID: 40525942
Looking for something a little more dynamic if i need it to fill 20 spaces and can calulate based on if the string as 5 letters or 10 leters.
0
 

Author Comment

by:desiredforsome
ID: 40525947
here is my code so far but not accurate

becasue the date stirng that is in there is supposed to start on the 35th character with a max of 11 characters in that string.

So code below
string eh = string.Format("{0}", "EH");
            string instid = string.Format("{0,6}", "");
            string instname = string.Format("{0,25}", "");

            string date = string.Format("{0,11}", "20141231");
            string envelope = string.Format("{0,9}", "ENV16");
            string name=textBox1.Text + " " + textBox2.Text + " " + textBox3.Text;
            using (StreamWriter writer = new StreamWriter(@"C:\Users\cgashlin.MORGANFINANCIA0\Desktop\test1003.txt"))
            {

               
                StringBuilder sb = new StringBuilder();
                sb.Append(eh) ;
                sb.Append(instid);
                sb.Append(instname);
                sb.Append(date);
                sb.Append(envelope);
                sb.Append(Environment.NewLine);
                sb.Append("02C"+  string.Format("{0,4}", name));
                writer.Write(sb.ToString());

Open in new window


Produces
EH                                  20141231    ENV16

Open in new window


However the spacing is not correct and I need it to be.

Here is my goal in spacing
EH                                20141231   ENV14  

Open in new window

string eh = string.Format("{0}", "EH");
            string instid = string.Format("{0,6}", "");
            string instname = string.Format("{0,25}", "");

            string date = string.Format("{0,11}", "20141231");
            string envelope = string.Format("{0,9}", "ENV16");
            string name=textBox1.Text + " " + textBox2.Text + " " + textBox3.Text;
            using (StreamWriter writer = new StreamWriter(@"C:\Users\cgashlin.MORGANFINANCIA0\Desktop\test1003.txt"))
            {

               
                StringBuilder sb = new StringBuilder();
                sb.Append(eh) ;
                sb.Append(instid);
                sb.Append(instname);
                sb.Append(date);
                sb.Append(envelope);
                sb.Append(Environment.NewLine);
                sb.Append("02C"+  string.Format("{0,4}", name));
                writer.Write(sb.ToString());

Open in new window

string eh = string.Format("{0}", "EH");
            string instid = string.Format("{0,6}", "");
            string instname = string.Format("{0,25}", "");

            string date = string.Format("{0,11}", "20141231");
            string envelope = string.Format("{0,9}", "ENV16");
            string name=textBox1.Text + " " + textBox2.Text + " " + textBox3.Text;
            using (StreamWriter writer = new StreamWriter(@"C:\Users\cgashlin.MORGANFINANCIA0\Desktop\test1003.txt"))
            {

               
                StringBuilder sb = new StringBuilder();
                sb.Append(eh) ;
                sb.Append(instid);
                sb.Append(instname);
                sb.Append(date);
                sb.Append(envelope);
                sb.Append(Environment.NewLine);
                sb.Append("02C"+  string.Format("{0,4}", name));
                writer.Write(sb.ToString());

Open in new window

0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40525953
This specifier , "{1,-17}", states that the second field can have any number of characters from 0 - 17 left justified where the third field will always start at position 20. I think that is dynamic.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40525964
It would be easier if you specify what fields should be printed giving starting column and its width. Then we can come up with the correct formatting of the data.
0
 

Author Comment

by:desiredforsome
ID: 40529242
There are tons of these that will be happening in the end as I am working on fannie mae file format stuff.

What string.format would I use in order for a string to start on the 9th place that is 20 characters in total even though it will only have 5 characters.

"         tests               "
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40529259
Given that you want to construct a string having the first field being empty and a width of 9 and the second field having a width of 20 and being left justified the following string format specifier, "{0,9}{1,-20}", will produce that result as shown in the code snippet below.

string field1 = "";
string field2 = "tests";

string result = String.Format("{0,9}{1,-20}", field1, field2);

// result will contain the string "         tests               "

Open in new window

0
 

Author Comment

by:desiredforsome
ID: 40530170
Any good information on using that context with string.format? I Would liek to understand it as it just is not producing the results I would like to see.

The one previous wasw an example.

However

feild 1 could be 3 or 5 characters.
feild2 would always start on the 9th place of the line from 0 and the feild2 would be no longer than 20 characters thus having he next field (feild3) start on the 20th character
0
 

Author Comment

by:desiredforsome
ID: 40530185
So What it is looking like is that I need the starting charcter to start on the specified place and not ending on the specific place holder. so if i use a example like "tests" and have it do {0,9} then it movies it over until it ends on the 9th. I woudl like it to start on the 9th. NO matter what the string actually is.
0
 

Author Comment

by:desiredforsome
ID: 40530187
Also with a maxium width.
0
 

Author Comment

by:desiredforsome
ID: 40530192
Maybe it would be easier if I wrote it like this.


String feild1 = "feield1";
String field2 = "feidl2";
String feidl3 = "feidl3";

I want field1 to start at the 0 position on a line for the text file with a maximum number of characters of 10. However feild1 can be up to 10 characters it can say "Field1" or "FIelds01" it does not matter.

Then on the 11th position in the same line field2 must start with a maximum characters of 14. Again same thing it does not matter what the string actually is.

Field 3 will start on the 25th position on the line.
and so on.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 40530278
To your statement, "I want field1 to start at the 0 position on a line for the text file with a maximum number of characters of 10. However feild1 can be up to 10 characters it can say "Field1" or "FIelds01" it does not matter."

To do this you would need this specifier.
"{0,-10}"

To your statement, "Then on the 11th position in the same line field2 must start with a maximum characters of 14. Again same thing it does not matter what the string actually is.",

To do this you would need this specifier.
"{1,-14}"

To your statement, "Field 3 will start on the 25th position on the line. and so on."

To do this you would need this specifier. Where XX needs to be replaced with the max field width.
"{2,-XX}"

So your sample code would be

String feild1 = "feield1";
String field2 = "feidl2";
String feidl3 = "feidl3";

string output = String.Format("{0,-10}{1,-14}{2,-XX}...",  field1, field2, field3, ...);

Please read through the Microsoft documentation on String.Format Method.
0
 

Author Closing Comment

by:desiredforsome
ID: 40530671
This makes sense now. I thank you very much this should solve all my issues :-) A+++++
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40530692
Not a problem desiredforsome, glad to help..
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Help with sorting data in Listbox using VB.NET 3 53
Need help on C# Linq query on object 6 53
Not showing JavaScript in the list 5 37
Run time Error 4 34
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now