Problems writing a pound (sterling) sign to a file

C

Colby

Using the following code I am trying to write to a text file. I keep
getting "£"

All I want is "£"

Any Ideas?



using System;

using System.IO;

using System.Text;

public class TextToFile

{

private const string FILE_NAME = "MyFile.txt";

public static void Main(String[] args)

{



if (File.Exists(FILE_NAME))

{

Console.WriteLine("{0} already exists.", FILE_NAME);

return;

}


StreamWriter sr = File.AppendText(FILE_NAME);



sr.WriteLine ("£");

sr.Close();

}

}
 
N

Nicholas Paldino [.NET/C# MVP]

Colby,

Instead of calling the AppendText method, create the StreamWriter
instance yourself, using a FileStream instance, and pass the encoding to the
StreamWriter that the character is a part of. The AppendText method makes
some assumptions about the encoding which is probably what is causing your
problem.

Hope this helps.
 
J

Jon Skeet

Colby said:
Using the following code I am trying to write to a text file. I keep
getting "£"

No, you're getting "£" in UTF-8 (I believe), which is the default
encoding for StreamWriter. Now, what encoding do you *want* your stream
to be in?
 
Joined
Feb 22, 2006
Messages
1
Reaction score
0
Try this

The problem comes from the ASCII encoder in .net it only deals with the lower 128 chars and £ is 163.. try this.
// Get a byte array holding ASCII encoded chars for a string.

// with the £ symbol correctly converted.

publicbyte[] RemovePound(string OrigionalString, string FileName)

{

// Get the string in char form.

char[] UniCodeCharArray = OrigionalString.ToCharArray();

// Create storage for the resulting ASCII Byte array.

byte[] ResultingByteArray = newbyte[OrigionalString.Length];

// ooh a little county thing..

int i = 0;

// ok.. for each character in the origional string

foreach (char c in UniCodeCharArray)

{

// Get the ASCII value for this character (substituting £££'s)

byte NewByte = (c == 163) ? ((byte)163) : ((byte)ASCIIEncoding.ASCII.GetBytes(UniCodeCharArray, i, 1).GetValue(0));

// Store this in our results array.

ResultingByteArray = NewByte;

// Move on.

i++;

}

// now it's all converted lets save it!

FileStream fs = newFileStream(FileName, FileMode.OpenOrCreate);

fs.Write(ResultingByteArray, 0, ResultingByteArray.Length);

fs.Flush();

fs.Close();

// Return the results and everyone is happy!!

return ResultingByteArray;

}

hope it helps :p
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top