如何将变量值写入文件

时间:2014-07-22 21:30:31

标签: c#

我有以下代码读取文本文件并计算单词出现的次数,然后将其保存到变量中:

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)
            {
            }
        }

当我点击按钮时,它应该将变量k写入WhatFound.txt,但不会发生任何事情。

我该如何解决?

3 个答案:

答案 0 :(得分:1)

您的代码可能存在不同的问题。正如@ tier1所说,它可能是一个例外。此外,您应该关闭流。一个更简单的替代方案可能是

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

(它当然可能会抛出异常。一般情况下,最好避免空的catch-all块。)

答案 1 :(得分:1)

您是否测试过k变量是否为空?

也许工作正常并正在写一些东西,但是如果k为空,那么它应该显示为没有任何反复发生。

尝试类似:

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

最后一块......

编辑:正如AlexD所说:更好地使用

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

                }
            }

这里有链接:

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

OLD:

关闭流

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

答案 2 :(得分:1)

除了Oscar Bralo和AlexD提到的那些问题之外还有另外一个问题:你跳过第一个字。

我相信你应该做到以下几点:

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

在您的原始代码中,您开始了#34;我&#34;在一个:

            int i = 1;

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