C#笔记1## C#笔记—文本读写
using System;
using System.IO;
public class Duxie
{
public double[,] input_matrix()
{
double[,] input_matrix = new double[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
input_matrix[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
return input_matrix;
}
public void Writeto(double[,] arr) //保存txt文本
{
//获取当前时间 年月日时分秒 大写的MM是月,小写的mm是分钟 ss是秒
string name = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
//保存地址为D盘,文件名根据系统时间自创
FileStream fs = new FileStream("D:\\C#_text\\" + name + ".txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//初始化二维数组s 用来接收arr
double[,] s = new double[4, 4];
//接收arr
s = arr;
for (int l = 0; l < 4; ++l)
{
for (int h = 0; h < 4; ++h)
{
//s的每个值和arr的每个值对应
s[l, h] = arr[l, h];
int output;
output = Convert.ToInt32(s[l, h]);
//有个空格作为间隔,
sw.Write(output + " ");
}
sw.WriteLine();
}
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
public double[,] Readin() //保存txt文本
{
int counter = 0;
string line;
// Read the file and display it line by line.
//FileStream fs = new FileStream("D:\\C#_text\\" + name + ".txt", FileMode.Create);
// StreamWriter sw = new StreamWriter(fs);
StreamReader file = new StreamReader(@"D:\C#_text\matrix_3_3.txt");
double[,] matrix = new double[4, 4];
while ((line = file.ReadLine()) != null)
{
string[] line1 = System.Text.RegularExpressions.Regex.Replace(line.Trim(), @"[\s]+", " ").Split(" ".ToCharArray());
matrix[counter, 0] = Convert.ToDouble(line1[0]);
matrix[counter, 1] = Convert.ToDouble(line1[1]);
matrix[counter, 2] = Convert.ToDouble(line1[2]);
matrix[counter, 3] = Convert.ToDouble(line1[3]);
for (int i = 0; i < 4; i++)
Console.Write(matrix[counter, i] + " ");
Console.WriteLine();
// System.Console.WriteLine(line);
counter++;
}
file.Close();
Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
//Console.ReadLine(); 如果加上这句则需要再读入一个输入才能跳出该程序转入下一程序
return matrix;
}
}
class WriteTextFile
{
static void Main()
{
Duxie mani = new Duxie();
//string path= "matrix_3_3.txt";
double[,] goal = mani.Readin();
mani.Writeto(goal);
}
}