Determining size of a future file while data is still in memory
<p>This is C#/.NET 2.0.</p>

<p>So I have string that contains the future contents of an XML file. It contains metadata and binary data from image files. I would like to somehow determine how big the XML file will be once I write the data in the string to the file system.</p>

<p>I've tried the following and neither works:</p>

<pre><code>Console.Out.WriteLine("Size: " + data.Length/1024 + "KB");
</code></pre>

<p>and</p>

<pre><code>Console.Out.WriteLine("Size: " + (data.Length * sizeof(char))/1024 + "KB");
</code></pre>

<p>Neither works (the actual size of the resulting file deviates from what is returned from either of these methods). I'm obviously missing something here. Any help would be appreciated.</p>

<p>XML Serialization:</p>

<pre><code>// doc is an XMLDocument that I've built previously
StringWriter sw = new StringWriter();
doc.Save(sw);
string XMLAsString = sw.ToString();
</code></pre>

<p>Writing to file system (XMLAsString passed to this function as variable named data):</p>

<pre><code>Random rnd = new Random(DateTime.Now.Millisecond);   
FileStream fs = File.Open(@"C:\testout" + rnd.Next(1000).ToString() +  ".txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
app.Diagnostics.Write("Size of XML: " + (data.Length * sizeof(char))/1024 + "KB");
sw.Write(data);
sw.Close();
fs.Close();
</code></pre>

<p>Thanks</p>
