Error reading a file

Romulo

Member
Joined
Dec 11, 2013
Messages
8
Programming Experience
1-3
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;
        }


    }
}
 
If it's telling you that the file doesn't exist then the file doesn't exist. That's not an error reading the file. The file would have to exist for there to be an error reading it.

Are you specifying just the file name? If so then it will assume that the folder path is the current directory for your application, which is the program folder by default. If you want it to look in a specific folder for the file then you have to tell it the path of that folder.
 
Back
Top Bottom