2011-11-02 12 views
18

Ho il seguente programma che invierà (output) informazioni a un file di testo, ma ora voglio leggere (input) dal file di testo. Ogni suggerimento sarà molto apprezzato. Ho commentato un paio di cose che "penso" ho bisogno di fare; ma non sono veramente sicuro di come procedere.Lettura da un file di testo in C#

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; 
     } 
    } 
} 

risposta

5

Prova questo:

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

Sarà leggere tutti i dati dal file selezionato nella variabile fileText.

44

Per leggere un file di testo una riga alla volta si può fare in questo modo:

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. 
    } 
} 

Non ci sono altri modi. Ad esempio, se il file non è troppo grande e si vuole proprio tutto di leggere ad una singola stringa, è possibile utilizzare File.ReadAllText()

myTextBox.Text = File.ReadAllText(fileName); 
-1

Controllare questo codice:

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 
9

E 'solo una riga di codice :

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

Usa Split(), come nel seguente codice

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); 
 
       } 
 
      } 
 
      
 
     } 
 
     
 
    } 
 
} 
 
​

0
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); 
      } 


     } 
    } 
} 
0

Programma di esempio dimostrando I/O file 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; 
    } 
}