Question : File Size vs String Size

How can I compare the size of a file to the size of a string?

I am trying to determine whether a file should be overwritten with the contents of a string or not based on the file size

Answer : File Size vs String Size


It depends on how you write the data to file and your requirement.

For the standard ASCII and UT8 encodings (which will cover english and similar other charsets), string length and file byte length will match, as one character takes only byte in file.

For Unicode encodings (like japanese chars), as you said string length and file byte length will not match as one character will take two bytes.

Below is the code for both the encodings, you can use as per your requirement.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
For the standard encodings (ASCII, UTF8):

	   string textToWrite = "12345";

            string path = @"c:\temp\MyTest.txt";
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists || textToWrite.Length > fi.Length)
            {
                using (StreamWriter sw = fi.CreateText())
                {
                    sw.Write(textToWrite);
                }
            }


For Unicode encoding:

	    string textToWrite = "12345";

            byte[] bytesToWrite = System.Text.Encoding.Unicode.GetBytes(textToWrite);
           
            string path = @"c:\temp\MyTest.bytes";
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists || bytesToWrite.Length > fi.Length)
            {
                using (FileStream sw = fi.Create())
                {
                    sw.Write(bytesToWrite, 0, bytesToWrite.Length);
                }
            }
Random Solutions  
 
programming4us programming4us