Hurrem
Hurrem

Reputation: 183

streamWrite doesn't work

I'm trying to read file into a string and rewrite that string into a new file, but there is a small check, if the current character is one of special characters that I want to rewrite. I've debugged it, and the code seems to work fine, but the output file is empty.. I think I'm missing something... but what?

StreamWriter file = new StreamWriter(newname, true);

char current;
int j;
string CyrAlph = "йцукен";
string LatAlph = "ysuken";
string text = File.ReadAllText(filename);

for (int i = 0; i < text.Length; i++)
{
    if (CyrAlph.IndexOf(text[i]) != -1)
    {
        j = CyrAlph.IndexOf(text[i]);
        current = LatAlph[j];

    }
    else current = text[i];

    file.Write(current);
}

Upvotes: 2

Views: 920

Answers (3)

C&#233;dric Bignon
C&#233;dric Bignon

Reputation: 13022

StreamWriter implements IDisposable. You "have" to Dispose it after using it. To do so, use a using statement. This will automatically flushes and closes the stream at the end of the using body.

using(StreamWriter file = new StreamWriter(newname,true))
{
    char current;
    int j;
    string CyrAlph="йцукен";
    string LatAlph = "ysuken";
    string text = File.ReadAllText(filename);

    for (int i = 0; i < text.Length; i++)
    {
        if (CyrAlph.IndexOf(text[i]) != -1)
        {
            j=CyrAlph.IndexOf(text[i]);
            current = LatAlph[j];

        }
        else current=text[i];

        file.Write(current);
    }
}

Upvotes: 0

steinar
steinar

Reputation: 9673

You're missing a stream flush. The standard pattern is to add a using statement around the allocation of the StreamWriter. That also takes care of closing the file and releasing the operating system's file handle:

using (StreamWriter file = new StreamWriter(path, true))
{
   // Work with your file here

} // After this block, you have "disposed" of the file object.
  // That takes care of flushing the stream and releasing the file handle

The using statement has the added benefit, over explicitly closing the stream, of disposing the stream correctly even in the case of an exception within the block.

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67135

What happens if you set file.AutoFlush = true after your StreamWriter instantiation or call file.Close at the end of writing everything or you can instantiate your StreamWriter in a using statement. My guess is that it is empty because the buffer needs flushed

Upvotes: 1

Related Questions