473,888 Members | 1,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Format fixed length fields with leading zeros or spaces


Hi,

I am somewhat new to .net and c#. (What I learned in previous co has to
be unlearned). I am doing something that seems simple but I think there
is a better way than how I learned to do it. I am creating a fixed
length file with fixed length fields. Each field either requires
leading zeros or added on spaces. I learned to create a helper class
and for every field do this:
public static string FormatFieldA(st ring str12)
{
if (str12 == null || str12.Trim() == "")
//Default spaces required length = 12
{
return " ";
}
else
{
Int32 l = 12 - str12.Trim().Le ngth;
if (l != 0)
for (int i = 1; i <= l; i++)
{
str12 = str12 + " ";
}
return str12;

}
}
I think there must be a better way like specifying in the Header or
Detail class for each field the field length and whether leadingzero is
t/f and then pass each field with those values to a simple format
function. But I don't know if that is the best way and I don't know how
to assign those constants. Could someone help? I want to do this well.

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #1
5 3453
Rowan <an***********@ yahoo.comwrote:
I am somewhat new to .net and c#. (What I learned in previous co has to
be unlearned). I am doing something that seems simple but I think there
is a better way than how I learned to do it. I am creating a fixed
length file with fixed length fields. Each field either requires
leading zeros or added on spaces. I learned to create a helper class
and for every field do this:
<snip>
I think there must be a better way like specifying in the Header or
Detail class for each field the field length and whether leadingzero is
t/f and then pass each field with those values to a simple format
function. But I don't know if that is the best way and I don't know how
to assign those constants. Could someone help? I want to do this well.
One way would be to have a custom attribute describing each field.
Fetch the attributes at execution time and call formatting methods
appropriately. Alternatively you could use an interface to specify (on
each class) what the field length should be.

One thing to point out though: String.PadRight and String.PadLeft are
your friends :)

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2
On May 14, 2:30*pm, Rowan <anonymous1...@ yahoo.comwrote:
Hi,

I am somewhat new to .net and c#. (What I learned in previous co has to
be unlearned). *I am doing something that seems simple but I think there
is a better way than how I learned to do it. *I am creating a fixed
length file with fixed length fields. *Each field either requires
leading zeros or added on spaces. *I learned to create a helper class
and for every field do this:
* * * *public static string FormatFieldA(st ring str12)
* * * * {
* * * * * * if (str12 == null || str12.Trim() == "")
* * * * * * //Default spaces required length = 12
* * * * * * {
* * * * * * * * return " * * * * * *";
* * * * * * }
* * * * * * else
* * * * * * {
* * * * * * * * Int32 l = 12 - str12.Trim().Le ngth;
* * * * * * * * if (l != 0)
* * * * * * * * * * for (int i = 1; i <= l; i++)
* * * * * * * * * * {
* * * * * * * * * * * * str12 = str12 + " ";
* * * * * * * * * * }
* * * * * * * * return str12;

* * * * * * } * *
* * * * }
I think there must be a better way like specifying in the Header or
Detail class for each field the field length and whether leadingzero is
t/f and then pass each field with those values to a simple format
function. *But I don't know if that is the best way and I don't know how
to assign those constants. Could someone help? *I want to do this well.
Look into the String.Format method. One thing, you will need to change
the datatype of the value to be padded to a numeric datatype.

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Jun 27 '08 #3
On May 14, 2:30*pm, Rowan <anonymous1...@ yahoo.comwrote:
Hi,

I am somewhat new to .net and c#. (What I learned in previous co has to
be unlearned). *I am doing something that seems simple but I think there
is a better way than how I learned to do it. *I am creating a fixed
length file with fixed length fields. *Each field either requires
leading zeros or added on spaces. *I learned to create a helper class
and for every field do this:
* * * *public static string FormatFieldA(st ring str12)
* * * * {
* * * * * * if (str12 == null || str12.Trim() == "")
* * * * * * //Default spaces required length = 12
* * * * * * {
* * * * * * * * return " * * * * * *";
* * * * * * }
* * * * * * else
* * * * * * {
* * * * * * * * Int32 l = 12 - str12.Trim().Le ngth;
* * * * * * * * if (l != 0)
* * * * * * * * * * for (int i = 1; i <= l; i++)
* * * * * * * * * * {
* * * * * * * * * * * * str12 = str12 + " ";
* * * * * * * * * * }
* * * * * * * * return str12;

* * * * * * } * *
* * * * }
I think there must be a better way like specifying in the Header or
Detail class for each field the field length and whether leadingzero is
t/f and then pass each field with those values to a simple format
function. *But I don't know if that is the best way and I don't know how
to assign those constants. Could someone help? *I want to do this well.

*** Sent via Developersdexht tp://www.developersd ex.com***

Take a look at PadLeft/PadRight.

In your case can be myFieldValue.To String().PadLef t( sizeOfField,
charToFillWith) ;
Jun 27 '08 #4
Okay, the padding part makes sense. I am a little lost when it comes to
the custom attributes. I think I would need

[AttributeUsage( AttributeTarget s.Field, AllowMultiple = false)]

Where does this go? Does it get it's own class like public class
MyFieldsAttribu te or because it is field level does it go in the class I
am using the attributes for? I need an attribute for requiredlength
(int) and leadingzeros (bool)...where does it go? I am finding a lot to
read about it but not quite understanding where everything goes...help
is very greatly appreciated.

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #5
Rowan <an***********@ yahoo.comwrote:
Okay, the padding part makes sense. I am a little lost when it comes to
the custom attributes. I think I would need

[AttributeUsage( AttributeTarget s.Field, AllowMultiple = false)]

Where does this go? Does it get it's own class like public class
MyFieldsAttribu te or because it is field level does it go in the class I
am using the attributes for?
The attribute type itself is just a class, even though it's applied to
fields. I wouldn't make it a nested class.
I need an attribute for requiredlength
(int) and leadingzeros (bool)...where does it go? I am finding a lot to
read about it but not quite understanding where everything goes...help
is very greatly appreciated.
See if http://msdn.microsoft.com/en-us/libr...54(VS.71).aspx
helps you.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
9710
by: Adrian Parker | last post by:
I'm using the code below in my project. When I print all of these fixed length string variables, one per line, they strings in questions do not properly pad with 0s. strQuantity prints as " 4". Six spaces than the value of intQuantity. This is correct. But all the others end up being string objects of only 6 characters long (with the exception of strTotal). The left most positions of the string object are being padded with one...
1
2637
by: Andrew | last post by:
I run a fixed-width export based on a query, and the query looks like this... Clients.SSN, Clients.ClientID, ServiceEvents.SeviceDate, CStr(Format(,"0000")) AS Servs, "28" AS SETTING, FROM Clients INNER JOIN ServiceEvents ON Clients.AutoID=ServiceEvents.AutoID WHERE ServiceEvents.Sub=False; Now, this looks fine when I few the query, and the "Unit" field is 4
3
2324
by: John B | last post by:
I'm receiving a fixed length string with fixed length fields that I need to break apart. Ideally I'd like to take the string and put it into a Structure and then access the individual fields from there. I tried converting the string to a byte array and then used a Marshal.PtrToStructure to do the move but get a null reference exception in mscorlib.dll. All the paramers look valid going into the call. Any ideas how to fix the error or...
5
3136
by: David Garamond | last post by:
The MySQL manual recommends that we create a "fixed-length row" if possible, for speed (especially scanning speed). A fixed-length row is a row which is comprised of only fixed-length fields. A fixed-length field takes a fixed amount of bytes for storage (e.g. INT = 4 bytes, CHAR(M) = M bytes, etc). Is there a similar recommendation in PostgreSQL? I notice that most data types are stored in variable-length mode anyway (is cidr and inet...
2
5626
by: Frank Swarbrick | last post by:
I'm just learning about embedded SQL, so be gentle... My basic question is, if I use a fixed length host variable for a column defined as VARCHAR, will trailing spaces be removed (or not) upon INSERT or UPDATE of this column? I tried it, and it appears they are *not* stripped. However, the Programming Client Applications manual leads me to believe that the spaces should be stripped. A quote from that manual: -------------------------...
1
1611
by: htres | last post by:
Hello, I'm new to programming and C#, so please bear with my ignorance! I need to extract jpeg images and header data from a binary file. The binary file is formatted with several fixed length fields containing information about the jpeg image, followed by the jpeg itself, followed by more header data, another jpeg, etc... Using a FileStream and BinaryReader I am able to read and store the metadata, because I know the length of the...
6
7774
by: JimmyKoolPantz | last post by:
Task: Customer wants a script of the data that was processed in a "CSV" file. Problem: Zip-Code leading zeros are dropped Basically we have a client that has requested a custom script for each file that he has us process. He wants this in a Comma Delimited Format.
4
2821
by: Scotty | last post by:
Hi everyone, Is there an equivalent to vb6 Dim test as String * 40 ? I have been looking for a solution but no luck until now. Any help would be greatly appreciated.
0
4115
by: Monty | last post by:
Hi All, I am having a problem with leading zeros being stripped from fields in a CSV file when I bring them in using Jet/OleDB. In VB.Net/VS 2008, I am accessing a CSV file like so: sSQL = "SELECT * FROM " sConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ Microsoft.VisualBasic.FileIO.FileSystem.GetParentPath(msFile) & _
0
9959
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10772
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10880
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10434
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7144
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5812
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6012
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3246
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.