views:

260

answers:

2

Hi, I have a serial number which is String type.

Like This;

String.Format("{0:####-####-####-####}", "1234567891234567" );

I need to see Like This, 1234-5678-9123-4567;

Bu this Code does not work?

Can you help me?

+2  A: 

That syntax takes an int, try this:

String.Format("{0:####-####-####-####}", 1234567891234567);

Edit: If you want to use this syntax on a string try this:

String.Format("{0:####-####-####-####}", Convert.ToInt64("1234567891234567"))
Yannick M.
No I can not do this;String mycode= "1234567891234567"; String.Format("{0:####-####-####-####}", mycode);I use diynamic serial number. So I use String variable.
atromgame
Also I use Decilam.Parse(),it is works too.
atromgame
Seems a bit convoluted to convert the `string` to a `long` only to convert it back to a `string` again.
LukeH
+2  A: 

For ####-####-####-####, you will need a number. But you're feeding it a string.

It would be more practical to pad the string with additional zero's on the left so it becomes exactly 16 characters. Then insert the dash in three locations inside the string. Converting it to an Int64 will also work but if these strings become bigger or start to contain non-numerics, then you will have a problem.

string Key = "123456789012345";
string FormattedKey = Key.PadLeft(16, '0').Insert(12, "-").Insert(8, "-").Insert(4, "-");

That should be an alternative to formatting. It makes the key exactly 16 characters, then inserts three dashes from right to left. (Easier to keep track of indices.)

There are probably plenty of other alternatives but this one works just fine.

Workshop Alex
So How Can I Format a string variable?
atromgame
To use the syntax you tried above, convert the string to an int
Yannick M.
Or use the alternate solution that I've added to my answer. :-)
Workshop Alex