Click here to Skip to main content
15,898,792 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am working on an hangman project. I completed everything. I am keeping words as an array such as below;
C#
string[] words = new string[10] { "SCHOOL", "COMPUTER", "BOOK", "STORY", "APPLE", "TRANSPARENT", "MEDITERRANEAN", "CAT", "RABBIT", "RANDOM" };

But I want to read them from a text file. I searched and found this. However, I cant apply to my project.
C#
{
          string line;
      //  openFileDialog1.Title = "Openfile";
      //  openFileDialog1.ShowDialog();
      //  StreamReader rdLine = new StreamReader(openFileDialog1.FileName);
          StreamReader rdLine = new StreamReader("C:/cmpe414/2012Fall/iostreamExample/sonuc.txt");
         while ((line = rdLine.ReadLine()) != null)
            {
                MessageBox.Show(line);
                textBox3.Text += line + (char)13 + (char)10;
            }
            rdLine.Close();
        }
Posted

By far the simplest way to do this would be to create a text file in Notepad, lets call it Hangman_Words.txt, with one word per line, e.g.
SCHOOL
COMPUTER
BOOK
etc...


and then read the file directly into a string array using the File.ReadAllLines method.
C#
string[] words = System.IO.File.ReadAllLines("c:\dir\Hangman_Words.txt");


That's it really.

[EDIT} and you see that OriginalGriff and I are in complete agreement.

Alan.
 
Share this answer
 
v3
Comments
FoxRoot 25-Nov-12 8:33am    
Firstly; System.IO.File.ReadAllLines this does not exist on my IDE(VS2010) and also I need to read words by words.
OriginalGriff 25-Nov-12 8:39am    
Um - yes it does... it's been part of .NET since at least version 2.0!
FoxRoot 25-Nov-12 8:44am    
Should I import something ?
The easiest way is to store your words one per line in your text file.
You can then read them all into a string arry with one statement:
C#
string[] words = File.ReadAllLines(path);
 
Share this answer
 
Comments
FoxRoot 25-Nov-12 8:31am    
But I want to read words by words. My text content is like that;
Cat Car Apple and so on
it should read words by words.
OriginalGriff 25-Nov-12 8:37am    
If they are separated by spaces, then you can read the file in using
string data = File.ReadAllText(path);
string[] words = data.Split(' ', '\n');
The Split will work on spaces and newlines, so it should cover short lines as well.
FoxRoot 25-Nov-12 8:44am    
string data = File.ReadAllText(path); in this, I am takin The File does not exist in the current context. Should I import something?
OriginalGriff 25-Nov-12 8:48am    
Add the using statement for System.IO
using System.IO;
FoxRoot 25-Nov-12 8:54am    
Thanks you so much! It works great. Have a nice day.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900