I'm trying to read a file to count the individual words in the file, but it always falls on the "else" statement. Put the file in the same directory but still don't work . Why would not be reading the file? You need to put the full path of the file? Have tried putting the full path and also did not work.
C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace exercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void CountWordsF(string inFileName)
{
int counter = 0;
string delim = " ,. ";
string[] fields = null;
string line = null;
if (File.Exists(inFileName))
{
var count = File.ReadAllText(inFileName).Split(' ').Count();
textBox2.Text = count.ToString();
}
else
{
textBox2.Text = "File does no exist"; //Always falls in else statement
}
}
private void CountButton_Click(object sender, EventArgs e)
{
string inFileName;
inFileName = textBox1.Text;
CountWordsF(inFileName);
}
public static int CountWords(string s)
{
MatchCollection collection = Regex.Matches(s, @"[\S]+");
return collection.Count;
}
}
}