Как работать с текстовыми файлами - C#
Формулировка задачи:
Уважаемые!
Для допуска к экзамену мне надо написать программу. Я выбрал C#. И почти вначале столкнулся с проблемой: в условии задания сказано создать базу данных в виде текстового файла, но с операциями работы с текстом в C# мне сталкиваться не приходилось.
Прошу помочь и написать здесь: как обратиться к файлу текста, как "вытащить" нужное предложение или слово из файла и т.д. Посоветуйте в каком тестовом редакторе лучше всего писать базу данных.
Решение задачи: «Как работать с текстовыми файлами»
textual
Листинг программы
using System;
using System.Windows.Forms;
using System.IO;
namespace DataGridViewExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Open the contact_list file for reading. File is placed in the debug folder.
StreamReader sr = new StreamReader("contact_list.txt");
// Variable to store each row.
string dataRow = "";
// String array needed to determin number of columns to use.
string[] headerRow;
int columns = 0;
// Object array used to store each line of data from the text file.
object[] row;
// Read the first line of the text file. Then split the data using a comma character
headerRow = sr.ReadLine().Split(',');
// Store the length of headerRow string array, this will tell us how many columns we need.
columns = headerRow.Length;
// "For Loop" below is used to add column headers to the DataGridView control. The name of each column
// header begins with "Header" followed by a number.
for (int cols = 0; cols < columns; cols++)
{
dgv.Columns.Add("Header " + cols, "Header " + cols);
}
// At this point, column headers have been added.
// Now all that remains is to add the rows. Read the file line by line, using a while loop
// and the ReadLine() method. When reading each line make sure it is not a blank line. If it is a blank line
// skip the line and read the next line.
while ((dataRow = sr.ReadLine()) != null)
{
if (dataRow != "")
{
row = dataRow.Split(','); // Split the dataRow string variable and store each data into an Object array.
dgv.Rows.Add(row); // Add the row.
}
}
}
}
}