我正在编写一个程序,我需要从一个文本文件中读取,写入和过滤数据到新的文件 该计划的主要目标是:
我有点坚持让程序一般写文件以及从文本文件中抓取某些字符。
如果有人能给我一些很棒的指示
谢谢!
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.Diagnostics;
using System.IO;
namespace Project_4_osmvoe
{
public partial class Form1 : Form
{
string ham;
StreamReader pizza;
StreamWriter burger;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = openFileDialog1.FileName;
}
pizza = new StreamReader(ham);
lblInputFile.Text = ham;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = saveFileDialog1.FileName;
}
burger = new StreamWriter(ham);
lblOutputFile.Text = ham;
}
private void button3_Click(object sender, EventArgs e)
{
string line;
while ((line = pizza.ReadLine()) != null)
{
if (filter(line))
burger.WriteLine(line);
}
pizza.Close();
burger.Close();
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}
}
}
答案 0 :(得分:6)
上述评论中收到的有用建议的一部分 (不要在事件之间保持流开放)
您认为这些线条的结果是什么?
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
Substring
的第二个参数是从字符串中提取的字符数。传递零意味着返回的字符串为空,因此后续测试始终为false,您永远不会写一行。
我建议在两个不同的全局变量中存储两个文件的名称,并在button3_Click中打开两个流
string inputFile;
string outputFile;
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
inputFile = openFileDialog1.FileName;
lblInputFile.Text = inputFile;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
outputFile = saveFileDialog1.FileName;
lblOutputFile.Text = outputFile ;
}
}
private void button3_Click(object sender, EventArgs e)
{
string line;
using(StreamReader pizza = new StreamReader(inputFile))
using(StreamWriter burger = new StreamWrite(outputFile))
{
while ((line = pizza.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line) && filter(line))
burger.WriteLine(line);
}
}
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 1);
string state = intext.Substring(0, 1);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}