简体   繁体   中英

Reading From a Text File in C#

I have the following program that will send (output) information to a text file, but now I want to read (input) from the text file. Any suggestions would be greatly appreciated. I have commented out a couple of things that "I think" I need to do; but I am not really certain how to proceed.

using System.Windows.Forms;
using System.IO;

namespace Input_Output
{
    public partial class Grades : Form
    {
        private StreamWriter output;

        private StreamReader input;


        public Grades()
        {
            InitializeComponent();
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnEnter.Visible = true;
            btnClose.Visible = true;
            txtFirst.Visible = true;
            txtLast.Visible = true;
            lblFirst.Visible = true;
            lblLast.Visible = true;
            listBox1.Visible = true;
            lblStatus.Visible = true;
            lblGrade.Visible = true;
            lblCourse.Visible = true;
            cmbID.Visible = true;
            lblID.Visible = true;
            txtCourse.Visible = true;
            txtGrade.Visible = true;
            lblStatus.Visible = true;

            DialogResult result;
            string fileName;
            using (SaveFileDialog chooser = new SaveFileDialog())
            {
                result = chooser.ShowDialog();
                fileName = chooser.FileName;
            }
            output = new StreamWriter(fileName);
            btnCreate.Enabled = false;
            txtFirst.Visible = true;
            txtLast.Visible = true;
            lblFirst.Visible = true;
            lblLast.Visible = true;
            btnEnter.Visible = true;
            btnClose.Visible = true;
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            //Close button pushes information from the listbox in to the text file

            output.Close();
            lblStatus.ForeColor = Color.Red;
            lblStatus.Text = "Output File";
            btnCreate.Enabled = true;
            listBox1.Items.Clear();
            cmbID.Text = "";
        }

        private void btnEnter_Click(object sender, EventArgs e)
        {
            // Enter button sends information to the list box, a Message Box prompts user to check for accuracy.  
            //Close button pushes information to the Text file.
            string last = "";
            string first = "";
            string course = "";
            string grade = "";

            if (txtFirst.Text != "" && txtLast.Text != "" && txtCourse.Text != "")
            {
                last = txtFirst.Text;
                first = txtLast.Text;
                course = txtCourse.Text;
                grade = txtGrade.Text;
                output.WriteLine (last + "\t"+ "\t" + first + ":"+ "\t" + cmbID.SelectedItem + "_" + course + "_" + grade );

                listBox1.Items.Add(txtLast.Text + "," + txtFirst.Text + ":" + cmbID.SelectedItem + "-" + txtCourse.Text + "-" + txtGrade.Text);
                lblStatus.ForeColor = Color.Navy;
                lblStatus.Text = "Entry Saved";
                txtFirst.Text = "";
                txtLast.Text = "";
                txtCourse.Text = "";
                txtGrade.Text = "";
                txtFirst.Focus();
            }
            else
            {     
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Empty text box or boxes";
            }
            MessageBox.Show("Please verify that the information is correct before proceeding");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Grades_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result;
            string fileName;
            using (OpenFileDialog chooser = new OpenFileDialog())
            {
                result = chooser.ShowDialog();
                fileName = chooser.FileName;
            }
            //while loop?
            //if variable is null, it's the end of the record
            //variable= !null 
            //txt read int variable TxtFile.Text += Rec + "\r\n";   while rec !=null;
        }
    }
}

To read a text file one line at a time you can do like this:

using System.IO;

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do stuff with your line here, it will be called for each 
        // line of text in your file.
    }
}

There are other ways as well. For example, if the file isn't too big and you just want everything read to a single string, you can use File.ReadAllText()

myTextBox.Text = File.ReadAllText(fileName);

这只是一行代码:

string content = System.IO.File.ReadAllText(@"C:\textfile.txt");

Try this:

if(result == DialogResult.OK && fileName != null)
{
    try
    {
        var fileText=File.ReadAllText(fileName);
    }
    catch(Exception ex)
    {
        //Handle exception here
    }
}

It will read all the data from the selected file into the fileText variable.

Use Split() like in the code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"C:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            string inputLine = "";
            List<List<int>> data = new List<List<int>>();
            while ((inputLine = reader.ReadLine()) != null)
            {
                string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (inputArray.Count() > 0)
                {
                    List<int> numbers = inputArray.Select(x => int.Parse(x)).ToList();
                    data.Add(numbers);
                }
            }

        }

    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace part_B_19
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                StreamReader sr = new StreamReader(@"C:\Users\Acer\Documents\Visual Studio 2012\Projects\combobox.txt");
                string line = sr.ReadLine();

                while (line != null)
                {
                    comboBox1.Items.Add(line);
                    line = sr.ReadLine();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
    }
}

Sample program demonstrating FILE i/o in C#

class Items
{
  public int itemID { get; set; }
  public string itemName { get; set; }
  public int itemNo { get; set; }
  public string pkgdate { get; set; }
}

class Program
{
  private static string connectionString = "...";

  static void Main(string[] args)
  {
    string streadpath = @"I:\itemdata.txt";
    string stwritepath = @"I:\itemdata1.txt";
    string stcopypath = @"I:\itemdata2.txt";

    List<Items> li_all = new List<Items>();
    List<Items> li_db = new List<Items>();
    List<Items> li_valid = new List<Items>();
    List<Items> li_invalid = new List<Items>();

    li_all = stread_file(streadpath);
    li_invalid = validate(li_all);
    li_db = retrievefromDB();
    bool x = stwrite_invalid(li_db, stwritepath);
    bool y = stcopy_file(streadpath, stcopypath);
  }

  static List<Items> stread_file(string stpath)
  {
    List<Items> stli = new List<Items>();
    using (StreamReader SR = new StreamReader(stpath))
    {
      string line = "";
      while ((line = SR.ReadLine()) != null)
      {
        string[] linevalues = line.Split(',');
        Items obj = new Items();
        obj.itemID = int.Parse(linevalues[0]);
        obj.itemName = linevalues[1];
        obj.itemNo = int.Parse(linevalues[2]);
        obj.pkgdate = linevalues[3];
        stli.Add(obj);
      }
    }
    return stli;
  }

  static List<Items> validate(List<Items> stli)
  {
    List<Items> li_valid = new List<Items>();
    List<Items> li_invalid = new List<Items>();
    DateTime parsed;
    foreach (Items stit in stli)
    {
      if(DateTime.TryParseExact(stit.pkgdate, "MM/dd/yyyy",
      CultureInfo.InvariantCulture,
      DateTimeStyles.None, out parsed))
      {
        li_valid.Add(stit);
      }
      else
      {
        li_invalid.Add(stit);
      }
    }
    InsertDataToDb(li_valid);
    return li_invalid;
  }

  static bool stwrite_invalid(List<Items> stli,string stpath)
  {
    using (StreamWriter SW = new StreamWriter(stpath))
    {
      foreach(Items stit in stli)
      {
        SW.WriteLine(stit.itemID + "," + stit.itemName + "," + stit.itemNo + "," + stit.pkgdate);
      }
    }
    return true;
  }

  static bool stcopy_file(string stsourcepath, string stdestinationpath)
  {
    File.Copy(stsourcepath, stdestinationpath);
    return true;
  }

  static void InsertDataToDb(List<Items> stli)
  {
    var records = stli;
    using (SqlConnection con = new SqlConnection(connectionString))
    {
      StringBuilder nonQuery = new StringBuilder();
      foreach (var item in records)
      {
        nonQuery.AppendFormat("INSERT INTO dbo.Smartphone VALUES ({0}, '{1}', {2}, '{3}');",
        item.itemID,
        item.itemName,
        item.itemNo,
        item.pkgdate);
      }
      SqlCommand cmd = new SqlCommand(nonQuery.ToString(),con);
      con.Open();
      cmd.ExecuteNonQuery();
      con.Close();
    }
  }

  static List<Items> retrievefromDB()
  {
    List<Items> stli = new List<Items>();
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from dbo.Smartphone", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);
    con.Close();
    if (dt.Rows.Count > 0)
    {
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        Items obj = new Items();
        obj.itemID = (int)dt.Rows[i]["ID"];
        obj.itemName = dt.Rows[i]["Name"].ToString();
        obj.itemNo = (int)dt.Rows[i]["Num"];
        obj.pkgdate = dt.Rows[i]["RDate"].ToString();
        stli.Add(obj);
      }
    }
    return stli;
  }
}

 namespace CDKatalog { public partial class KorisnickoUputstvo : System.Web.UI.Page { string[] izvodjac = new string[20]; string[] nazivAlbuma = new string[20]; string[] zanr = new string[20]; string[] godinaIzdavanja = new string[20]; string[] izdavackaKuca = new string[20]; string[] slikaOmota = new string[20]; protected void Page_Load(object sender, EventArgs e) { for (int i = 1990; i <= 2019; i++) { DropDownList2.Items.Add(i.ToString()); } StreamReader sr = File.OpenText(Server.MapPath(@"\\textFajl\\katalog.txt")); string sadrzaj = sr.ReadToEnd(); int brojac = 1; int j = 0; for (int i = 0; i < sadrzaj.Length; i++) { if (sadrzaj[i] == '^') { j++; brojac++; } else if (sadrzaj[i] == '|') { brojac++; } else if (brojac % 6 == 1) { izvodjac[j] = izvodjac[j] + sadrzaj[i]; } else if (brojac % 6 == 2) { nazivAlbuma[j] = nazivAlbuma[j] + sadrzaj[i]; } else if (brojac % 6 == 3) { zanr[j] = zanr[j] + sadrzaj[i]; } else if (brojac % 6 == 4) { godinaIzdavanja[j] = godinaIzdavanja[j] + sadrzaj[i]; } else if (brojac % 6 == 5) { izdavackaKuca[j] = izdavackaKuca[j] + sadrzaj[i]; } else if (brojac % 6 == 0) { slikaOmota[j] = slikaOmota[j] + sadrzaj[i]; } } } protected void Button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("Izvodjac", typeof(string)); dt.Columns.Add("Naziv Albuma", typeof(string)); dt.Columns.Add("Zanr", typeof(string)); dt.Columns.Add("Godina Izdavanja", typeof(string)); dt.Columns.Add("Izdavacka Kuca", typeof(string)); string pomoc = ""; for (int i = 1; i < 7; i++)//OVDE TREBA MENJATI BROJ { for (int c = 0; c < TextBox1.Text.Length; c++) { if (TextBox1.Text[c] == izvodjac[i][c + 2]) { pomoc = pomoc + TextBox1.Text[c]; } else { pomoc = ""; break; } } if (pomoc != "") { dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]); } } Label1.Text = nazivAlbuma[1][1].ToString(); GridView1.DataSource = dt; GridView1.DataBind(); } protected void Button2_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("Izvodjac", typeof(string)); dt.Columns.Add("Naziv Albuma", typeof(string)); dt.Columns.Add("Zanr", typeof(string)); dt.Columns.Add("Godina Izdavanja", typeof(string)); dt.Columns.Add("Izdavacka Kuca", typeof(string)); string pomoc = ""; for (int i = 1; i < 7; i++) { for (int c = 0; c < TextBox2.Text.Length; c++) { if (TextBox2.Text[c] == nazivAlbuma[i][c]) { pomoc = pomoc + TextBox2.Text[c]; } else { pomoc = ""; break; } } if (pomoc != "") dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]); } GridView1.DataSource = dt; GridView1.DataBind(); } protected void Button5_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("Izvodjac", typeof(string)); dt.Columns.Add("Naziv Albuma", typeof(string)); dt.Columns.Add("Zanr", typeof(string)); dt.Columns.Add("GodinaIzdavanja", typeof(string)); dt.Columns.Add("Izdavacka Kuca", typeof(string)); string pomoc = ""; for (int i = 1; i < 7; i++) { for (int c = 0; c < TextBox3.Text.Length; c++) { if (TextBox3.Text[c] == izdavackaKuca[i][c]) { pomoc = pomoc + TextBox3.Text[c]; } else { pomoc = ""; break; } } if (pomoc != "") dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]); } GridView1.DataSource = dt; GridView1.DataBind(); } protected void Button3_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("Izvodjac", typeof(string)); dt.Columns.Add("Naziv Albuma", typeof(string)); dt.Columns.Add("Zanr", typeof(string)); dt.Columns.Add("Godina Izdavanja", typeof(string)); dt.Columns.Add("Izdavacka Kuca", typeof(string)); for (int i = 0; i < 7; i++) { if (DropDownList1.SelectedValue == zanr[i]) { dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]); } } GridView1.DataSource = dt; GridView1.DataBind(); } protected void Button4_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Clear(); dt.Columns.Add("Izvodjac", typeof(string)); dt.Columns.Add("NazivAlbuma", typeof(string)); dt.Columns.Add("Zanr", typeof(string)); dt.Columns.Add("Godina Izdavanja", typeof(string)); dt.Columns.Add("Izdavacka Kuca", typeof(string)); for (int i = 0; i < 7; i++) { if (DropDownList2.SelectedValue == godinaIzdavanja[i]) { dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]); } } GridView1.DataSource = dt; GridView1.DataBind(); } } }

Check this code:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myStream As Stream = Nothing
    Dim openFileDialog1 As New OpenFileDialog()

    'openFileDialog1.InitialDirectory = "c:\"
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    openFileDialog1.FilterIndex = 1
    openFileDialog1.RestoreDirectory = True

    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try
            myStream = openFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then
                dataFile = openFileDialog1.FileName
                Label1.Text = openFileDialog1.SafeFileName

                Dim myReader As New StreamReader(dataFile)
                Dim line As String
                line = myReader.ReadLine()
                While Not (line Is Nothing)
                    Dim str() As String = Split(line, ControlChars.Tab)
                    ListView1.Items.Add(New ListViewItem(str))
                    line = myReader.ReadLine()
                End While

                myReader.Close()
            End If
        Catch Ex As Exception
            MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
        Finally
            ' Check this again, since we need to make sure we didn't throw an exception on open.
            If (myStream IsNot Nothing) Then
                myStream.Close()
            End If
        End Try
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM