Si8
Si8

Reputation: 9225

How to write a variable value to a file

I have the following code which reads in a text file and counts how many times a word appears and then saved it to a variable:

try
            {
                StreamReader sr = new StreamReader(@"C:\Readfile.txt");
                text = sr.ReadToEnd();

                string textData = Regex.Replace(text, @"[^0-9a-zA-Z]+", " ");

                char[] whitespace = new char[] { ' ', '\t' };
                string[] data = textData.Split(whitespace);
                int i = 1;

                while (i < data.Length)
                {
                    st = data[i];

                    string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);

                    var matchQuery = from word in source
                                     where word.ToLowerInvariant() == st.ToLowerInvariant()
                                     select word;

                    int wordCount = matchQuery.Count();
                    k += wordCount + ": " + st + "\n";
                    //MessageBox.Show(k);
                    i++;
                }
                StreamWriter sr4 = new StreamWriter(@"C:\WhatFound.txt");
                sr4.Write(k);

            }
            catch (Exception ce)
            {
            }
        }

When I click the button it should write the variable k to the WhatFound.txt but nothing is happening.

How can I fix it?

Upvotes: 1

Views: 334

Answers (3)

dbc
dbc

Reputation: 116795

One other possible problem in addition to those mentioned by Oscar Bralo and AlexD: you skip the first word.

I believe you should do the following:

for (int i = 0; i < data.Length; i++)
{
    // Process data[i]
}

In your original code you start "i" at one:

            int i = 1;

            while (i < data.Length)
            {
                // Process data[i]
                i++;
            }

Upvotes: 1

Oscar Bralo
Oscar Bralo

Reputation: 1907

Have you testes if you k variable is empty?

Maybe is working fine and is writting something, but if k is empty, then, it should appear as it nothing happened.

Try something like:

if(!string.IsNullOrEmpty(k)):
    //Then write in the text file

And in a finally block...

EDIT: As AlexD said: better use using

using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
            {
                foreach (DirectoryInfo dir in cDirs)
                {
                    sw.WriteLine(dir.Name);

                }
            }

Here the link:

http://msdn.microsoft.com/es-es/library/system.io.streamwriter(v=vs.110).aspx

OLD:

close the stream

try
{
}
catch
{
}
finally
{
    sr4.Close()
}

Upvotes: 1

AlexD
AlexD

Reputation: 32576

There can be different issues with your code. As @tier1 said, it can be an exception. Also, you should close the stream. A simpler alternative might be

File.WriteAllText(@"C:\WhatFound.txt", k);

(It still may throw an exception of course. In general it is better to avoid empty catch-all blocks.)

Upvotes: 2

Related Questions