C# 基本操作 (datagridview、流Stream(NetWorkStream)、文件读写FileStream、执行批处理文件(*.bat)、复制表、DataTable、数组)

prop 2次tab 出现:public int MyProperty { get; set; }


https://www.mockaroo.com/    数据模型
https://www.connectionstrings.com/ 数据库连接类


vs2010 解决中文提示突然变英文 


我的是64位操作系统,vs2010出现中文突然变英文,下面的方法解决了我这个问题

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\zh-Hans
下的XML文件
复制到
C:\Windows\Microsoft.NET\Framework\v2.0.50727\zh-CN
目录中

================================================================================================
“ResGen.exe”已退出,代码为 2


在PropertyGroup节点中加入“<ResGenToolArchitecture>Managed32Bit</ResGenToolArchitecture>”,保存文件。

================================================================================================
<AppSettings>
   <add key="config1" value="aaa" />
   <add key="config2" value="bbb" />
</AppSettings>
string str = System.Configuration.ConfigurationManager.AppSettings["config1"].ToString();//str等于aaa
string str1 = System.Configuration.ConfigurationManager.AppSettings["config2"].ToString();//str1等于bbb

================================================================================================


c#判断文件是否存在

if (!System.IO.File.Exists(filePath))
  {
      // don't find file
      return null;
  }

================================================================================================
1.DataSet DataTable DataView 互相转换
DataSet ds = new DataSet(); 
DataTable dt= new DataTable("Customers"); 
ds.Tables.Add(dt);

读取DataSet中某一个DataTable:
dt=ds.Tables[0];//指定第0个表
dt=ds.Tables["Customers"];//指定表名为“Customers”的表

DataView view1 = table.DefaultView;
DataView view2 = new DataView(table);

1 DataSet.Table[0].Rows[ i ][ j ]
         其中i 代表第 i 行数, j 代表第 j 列数
  
2 DataSet.Table[0].Rows[ i ].ItemArray[ j ]
        其中i 代表第 i 行数, j 代表第 j 列数
  
3 DataSet.Tables[0].Columns.Count
        取得表的总列数
  
4 DataSet.Tables[0].Rows.Count
       取得表的总行数
  
  
5 DataSet.Tables[0].Columns[ i ].ToString()
       取得表的 i 列名
  
注意:行和列的计算,都是从0开始  
 
1. 第一行第一列的值
 
      DataSet ds=new DataSet();
      ds.Tables[0].Rows[0][0].ToString();
 
2.第一行对应列的字段名
ds.Tables[0].Rows[0]["字段名"].ToString();
 
dbset.tables(0).rows(0).item("第一列的列名")
 
3. 行、列总数   DataSet_x.Tables[ "TableName "].Rows.Count
  DataSet_y.Tables[ "TableName "].Columns.Count 
 
4. 取某一列的值
 
   dataset.Tables["PersonInfo"].Rows[0]["age"].ToString();
 
5.向DataSet中插入新的一列
 

   DataSet ds = new DataSet();
   ds.Table[0].Columns.Add("字段名","字段类型");


   
6. 向DataSet中添加一行记录    dataset ds=new dataset();

 DataRow dr = ds.Tables[0].NewRow();
   dr["Finishdate"] = finishdate;
   dr["Operator"] =Operator;
   dr["disp"] =disp;
   ds.Tables[0].Rows.Add(dr);

   
7.DataTable转换为二维数组

DataTable dt = new DataTable();
int col = dt.Columns.Count;
string[,] array = new string[dt.Rows.Count,col];
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        array[i, j] = dt.Rows[i][j].ToString().ToUpper().Trim();
    }
}


================================================================================================
C#一维数组的声明方式
int[] myArray;

string[] myStrArr;

但是在访问数组之前必须初始化。

C#数组的初始化方式有两种,第一种是在声明数组的时候为数组的元素赋初值:
int[] myArray = { 5, 9, 15, 22, 30 };
string[] myStrArr = { "diagram", "league", "brambling" };

另一种方式需要在声明数组时指定数组的大小(即数组的长度,数组元素的个数):

int[] myArray = new int[5];
string[] myStrArr = new string[3];

当然不一定非是数值,也可以是带有常量(const)关键字的变量:

const int arrSize = 5;
int[] myArray = new int[arrSize];
string[] myStrArr = new string[arrSize];

访问数组元素可以通过for循环和数组元素对应的下标:

int[] myArray = { 5, 9, 15, 22, 30 };
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("数组长度为{0},第{1}个元素是:{2}", myArray.Length, i, myArray[i]);
}
Console.ReadKey();

还可以用foreach访问数组的每个元素,但foreach循环对数组的内容进行只读访问,所以不能改变任何元素的值:

int[] myArray = { 5, 9, 15, 22, 30 };
foreach (int num in myArray)
{
Console.WriteLine("数组元素为:{0}", num);
}
Console.ReadKey();


二维数组:


二维数组最简单的声明方式:
int[,] myIntArray;
string[,] myStrArray;


如下声明了一个4维数组:
int[,,,] myIntArray;


多维数组的声明方式只需要在二维数组的基础上添加多个逗号。

二维数组的初始化方式:

int[,] myIntArray = { { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 } };
string[,] myStrArray = new string[3, 2];


二维数组一样通过下标访问数组元素:


myIntArray[1,2];  // 8


myIntArray是一个3行3列的二维数组,所以myIntArray[1,2]中的1指的是数组myIntArray的第二个嵌套数组(数组下标识从0开始,所以1就是第二个了),myIntArray[1,2]中的2指的是数组myIntArray的第二个嵌套数组中的第三个元素,所以其值是8。


多维数组:


多维数组的两种声明和初始化方式,第一种:
int[][] myIntArrays = new int[2][];
myIntArrays[0] = new int[3];
myIntArrays[1] = new int[4];


另一种方式:


int[][] myIntArrays = {new int[]{1,2,3},new int[]{2,3,4,5}};


访问多维数组的元素可以用foreach循环:

int[][] myIntArrays = {new int[]{1,2,3},new int[]{2,3,4,5}};
foreach (int[] numArr in myIntArrays)
{
  foreach (int num in numArr)
  {
    Console.WriteLine("数组元素为:{0}", num);
  }
}


输出结果为:
数组元素为:1
数组元素为:2
数组元素为:3
数组元素为:2
数组元素为:3
数组元素为:4
数组元素为:5
================================================================================================
c#电脑桌面路径
string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);  

================================================================================================
获得datagridview 行索引

datagridview.CurrentCell.RowIndex;是当前活动的单元格的行的索引
datagridview.SelectedRows 是选中行的集合
datagridview.SelectedColumns 是选中列的集合
datagridview.SelectedCells 是选中单元格的集合 
DataGridView1.CurrentRow.Index 获得包含当前单元格的行的索引


C#中DatagridView的常用操作,有助于读者加深对C# DatagridView用法的理解,具体如下:
1、(最基本的技巧)、获取某列中的某行(某单元格)中的内容

this.currentposition = this.dataGridView1.BindingContext 
[this.dataGridView1.DataSource, this.dataGridView1.DataMember].Position;
bookContent = this.database.dataSet.Tables[0].Rows 
[this.currentposition][21].ToString().Trim();
MessageBox.Show(bookContent);


2、自定义列
//定义列宽
this.dataGridView1.Columns[0].Width = 80;
    继承 DataGridViewTextBoxCell 类生成新的Cell类,然后再继承 DataGridViewColumn 生成新的Column类,并指定
CellTemplate为新的Cell类。新生成的Column便可以增加到DataGridView中去。
3、自动适应列宽

DataGridView.AutoSizeColumns(
DataGridViewAutoSizeColumnCriteria.HeaderAndDisplayedRows);
DataGridView.AutoSizeColumn(
DataGridViewAutoSizeColumnCriteria.HeaderOnly,
2, false);
DataGridView.AutoSizeRow(
DataGridViewAutoSizeRowCriteria.Columns,
2, false);
DataGridView.AutoSizeRows(
DataGridViewAutoSizeRowCriteria.HeaderAndColumns,
0, dataGridView1.Rows.Count, false);

4、可以绑定并显示对象
Bind Objects to Windows Forms DataGridView Controls

5、可以改变表格线条风格

this.dataGridView1.GridColor = Color.BlueViolet;
this.dataGridView1.BorderStyle = BorderStyle.Fixed3D;
this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

6、动态改变列是否显示,和动态改变列的显示顺序

customersDataGridView.Columns["CustomerID"].Visible = false;
customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
customersDataGridView.Columns["City"].DisplayIndex = 2;
customersDataGridView.Columns["Country"].DisplayIndex = 3;
customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;

7、可以在列中显示图像

Icon treeIcon = new Icon(this.GetType(), "tree.ico");
DataGridViewImageColumn iconColumn = new DataGridViewImageColumn ();
iconColumn.Image = treeIcon.ToBitmap();
iconColumn.Name = "Tree";
iconColumn.HeaderText = "Nice tree";
dataGridView1.Columns.Insert(2, iconColumn);

8、格式化显示内容:

this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format = "d";
this.dataGridView1.DefaultCellStyle.NullValue = "no entry";
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewWrapMode.Wrap;
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment =DataGridViewContentAlignment.MiddleRight;

9、将指定列及以前的列固定不动
this.dataGridView1.Columns["AddToCartButton"].Frozen = true;
10、显示录入时出现的错误信息

private void dataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
// If the data source raises an exception when a cell value is
// commited, display an error message.
if (e.Exception != null &&
e.Context == DataGridViewDataErrorContext.Commit)
{
MessageBox.Show("CustomerID value must be unique.");
}}

11、大数据量显示采用Virtual Mode
Implement Virtual Mode in the Windows Forms DataGridView Control

12、设置指定的列只读
dataGridView1.Columns["CompanyName"].ReadOnly = true;

13、移去自动生成的列

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customerDataSet;
dataGridView1.Columns.Remove ("Fax");


或:

dataGridView1.Columns["CustomerID"].Visible = false;

14、自定义选择模式
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;

15、自定义设定光标进入单元格是否编辑模式(编辑模式)
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

16、新行指定默认值

private void dataGridView1_DefaultValuesNeeded
(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["Region"].Value = "WA";
e.Row.Cells["City"].Value = "Redmond";
e.Row.Cells["PostalCode"].Value = "98052-6399";
e.Row.Cells["Region"].Value = "NA";
e.Row.Cells["Country"].Value = "USA";
e.Row.Cells["CustomerID"].Value = NewCustomerId();
}

17、数据验证

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (e.FormattedValue.ToString() == String.Empty)
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}}}

18、数据提交到dataset中
 

DataSet ds = new DataSet("MyDataSet");
ds.Tables[biaom.Trim()].Rows.Clear();
try
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
DataTable dt = ds.Tables[biaom.Trim()];
DataRow myrow = ds.Tables[biaom.Trim()].NewRow();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
myrow[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
}
ds.Tables[biaom.Trim()].Rows.Add(myrow);
}
}
catch (Exception)
{
MessageBox.Show("输入类型错误!");
return;
} 

================================================================================================


必须要有自己的核心产品或擅长的方向,才有立足根本。否则都是昙花一现。

================================================================================================
1.DataTable[学习笔记]
//实例化一张表并定义表结构
      

  DataTable dt = new DataTable("IPtoHost");
        dt.Columns.Add("IPaddress");
        dt.Columns.Add("HostName");


        
        //该过程为将数据写入表中的第一行
      

  DataRow dr = dt.NewRow();
  dr["IPaddress"] = "172.16.124.254";
  dr["HostName"] = "MS-Computer";
  dt.Rows.Add(dr);


         //该过程为将数据插入表中的第二行
       

 DataRow dr = dt.NewRow();
  dr["IPaddress"] = "172.16.124.255";
  dr["HostName"] = "Rout";
   dt.Rows.Add(dr);


 创建表
 

//创建一个空表
DataTable dt = new DataTable();
//创建一个名为"Table_New"的空表
DataTable dt = new DataTable("Table_New");


创建列

//1.创建空列
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
//2.创建带列名和类型名的列(两种方式任选其一)
dt.Columns.Add("column0", System.Type.GetType("System.String"));
dt.Columns.Add("column0", typeof(String));
//3.通过列架构添加列
DataColumn dc = new DataColumn("column1",System.Type.GetType("System.DateTime"));
DataColumn dc = new DataColumn("column1", typeof(DateTime));
dt.Columns.Add(dc);


创建行

1.获取datarow列名:row.Talbe.Columns[index].ColumnName
2.获取datarow的值:row[i].ToString()

//1.创建空行
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
//2.创建空行
dt.Rows.Add();
//3.通过行框架创建并赋值
dt.Rows.Add("张三",DateTime.Now);//Add里面参数的数据顺序要和dt中的列的顺序对应 
//4.通过复制dt2表的某一行来创建
dt.Rows.Add(dt2.Rows[i].ItemArray);


赋值和取值

//新建行的赋值
DataRow dr = dt.NewRow();
dr[0] = "张三";//通过索引赋值
dr["column1"] = DateTime.Now; //通过名称赋值
//对表已有行进行赋值
dt.Rows[0][0] = "张三"; //通过索引赋值
dt.Rows[0]["column1"] = DateTime.Now;//通过名称赋值
//取值
string name=dt.Rows[0][0].ToString();
string time=dt.Rows[0]["column1"].ToString();


筛选行

//选择column1列值为空的行的集合
DataRow[] drs = dt.Select("column1 is null");
//选择column0列值为"李四"的行的集合
DataRow[] drs = dt.Select("column0 = '李四'");
//筛选column0列值中有"张"的行的集合(模糊查询)
DataRow[] drs = dt.Select("column0 like '张%'");//如果的多条件筛选,可以加 and 或 or
//筛选column0列值中有"张"的行的集合并按column1降序排序
DataRow[] drs = dt.Select("column0 like '张%'", "column1 DESC");


删除行

//使用DataTable.Rows.Remove(DataRow)方法
dt.Rows.Remove(dt.Rows[0]);
//使用DataTable.Rows.RemoveAt(index)方法
dt.Rows.RemoveAt(0);
//使用DataRow.Delete()方法
dt.Row[0].Delete();
dt.AcceptChanges();


//-----区别和注意点-----
//Remove()和RemoveAt()方法是直接删除
//Delete()方法只是将该行标记为deleted,但是还存在,还可DataTable.RejectChanges()回滚,使该行取消删除。
//用Rows.Count来获取行数时,还是删除之前的行数,需要使用DataTable.AcceptChanges()方法来提交修改。
//如果要删除DataTable中的多行,应该采用倒序循环DataTable.Rows,而且不能用foreach进行循环删除,因为正序删除时索引会发生变化,程式发生异常,很难预料后果。
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
  dt.Rows.RemoveAt(i);
}
复制表

//复制表,同时复制了表结构和表中的数据
DataTable dtNew = new DataTable();
dtNew = dt.Copy();
//复制表
DataTable dtNew = dt.Copy();  //复制dt表数据结构
dtNew.Clear()  //清空数据
for (int i = 0; i < dt.Rows.Count; i++)
{
    if (条件语句)
    {
         dtNew.Rows.Add(dt.Rows[i].ItemArray);  //添加数据行
    }
}
//克隆表,只是复制了表结构,不包括数据
DataTable dtNew = new DataTable();
dtNew = dt.Clone();
//如果只需要某个表中的某一行
DataTable dtNew = new DataTable();
dtNew = dt.Copy();
dtNew.Rows.Clear();//清空表数据
dtNew.ImportRow(dt.Rows[0]);//这是加入的是第一行


表排序

DataTable dt = new DataTable();//创建表
dt.Columns.Add("ID", typeof(Int32));//添加列
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Age", typeof(Int32));
dt.Rows.Add(new object[] { 1, "张三" ,20});//添加行
dt.Rows.Add(new object[] { 2, "李四" ,25});
dt.Rows.Add(new object[] { 3, "王五" ,30});
DataView dv = dt.DefaultView;//获取表视图
dv.Sort = "ID DESC";//按照ID倒序排序
dv.ToTable();//转为表


  
================================================================================================

c#确认对话框

DialogResult dr = MessageBox.Show("你确定要删除此信息?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
    //点确定的代码
    using (MAction action = new MAction("per", conn))
    {
        action.Delete(num);
    }
    SelectAll();
}
else
{
//点取消的代码
}


C#: 执行批处理文件(*.bat)的方法 

static void Main(string[] args)
{
    Process proc = null;
    try
    {                
        proc = new Process();
        proc.StartInfo.FileName = @"D:\adapters\setup\mybatch.bat";
        proc.StartInfo.Arguments = string.Format("10");//this is argument
        proc.StartInfo.CreateNoWindow = false;
        proc.Start();
        proc.WaitForExit();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception Occurred :{0},{1}", ex.Message,ex.StackTrace.ToString());
    }
}


运行时隐藏dos窗口

proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;


#############################################################


C#编程中经常会用到的一些流。比如说FileStream、MemoryStream、 BufferedStream、 NetWorkStream、 StreamReader/StreamWriter、 TextReader/TextWriter等的简单用法


一  FileStream类


     FileStream类主要用于读取磁盘上的文件或者向磁盘文件写入信息。有时,我们需要将程序中的一些数据存储到磁盘上或是读取配置文件中某些内容,在这里我们就会用该类。


     从磁盘上的文件中读取内容:

 FileStream file = File.Open(@"F:\file.txt", FileMode.Open); //初始化文件流
 byte[] array = new byte[file.Length];//初始化字节数组
 file.Read(array, 0, array.Length);//读取流中数据把它写到字节数组中
 file.Close();//关闭流
 string str = Encoding.Default.GetString(array);//将字节数组内容转化为字符串
 Console.WriteLine(str);


     将数据写入磁盘文件:

 FileStream file = File.Open(@"F:\file.txt", FileMode.Append);//初始化文件流
 byte[] array = Encoding.UTF8.GetBytes("Hello World!你好");//给字节数组赋值
 file.Write(array, 0, array.Length);//将字节数组写入文件流
 file.Close();//关闭流


二  MemoryStream类


     MemoryStream类主要用于操作内存中的数据。比如说网络中传输数据时可以用流的形式,当我们收到这些流数据时就可以声明MemoryStream类来存储并且处理它们。


     MemoryStream操作字符串:

string str = "Hi!你好!";
byte[] array = Encoding.UTF8.GetBytes(str);//将字符串转化为字节数组
MemoryStream memory = new MemoryStream(array);//初始化MemoryStream类
byte[] arrayNew = memory.ToArray();//将内存中的数据转换为字节数组
string strNew = Encoding.UTF8.GetString(arrayNew);//将字节数组转换为字符串


三  BufferedStream类


     BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。为什么要封装其他流类,这么做的意义是什么?按照微软的话说主要是减少某些流直接操作存储设备的时间。对于一些流来说直接向磁盘中存储数据这种做法的效率并不高,用BufferedStream包装过的流,先在内存中进行统一的处理再向磁盘中写入数据,也会提高写入的效率。


     将磁盘上的一个文件写入到磁盘上的另一个文件中:

 

 FileStream file1 = File.Open(@"F:\file1.txt", FileMode.OpenOrCreate,FileAccess.Read);//读取文件流
  FileStream file 2= File.Open(@"F:\file2.txt", FileMode.OpenOrCreate,FileAccess.Write);//写入文件流
  
  byte[] array = new byte[4096];
        
  BufferedStream bufferedInput = new BufferedStream(file1);//封装文件流
  BufferedStream bufferedOutput = new BufferedStream(file2);//封装文件流
  
  bufferedInput.Read(array, 0, array.Length);
 bufferedOutput.Write(array, 0, array.Length);
 
 int bytesRead = 0;
 while ((bytesRead = bufferedInput.Read(array, 0, 4096)) > 0)//读取到了数据
   {
     bufferedOutput.Write(array, 0, bytesRead);
     Console.WriteLine(bytesRead);
    }
 bufferedInput.Close();//关闭各种流
 bufferedOutput.Close();
 file1.Close();
 file2.Close();



     实际测试中,封装流的方法在效率上并没有太多的提升。使用其他流也可以封装文件流。如果想要保证不频繁的读取磁盘其实只要保证代码不这样做就可以了,所以其实在代码上多加控制,也能保证程序不会经常的操作磁盘。


 


NetWorkStream类


    NetWorkStream类是专门用来处理服务器与客户端通信的流。它在网络编程中经常使用,主要是用来处理类似Socket、TcpClient和TcpListener这些类中得到的流。


    简单的TCP同步方式服务器与客户端通信:

 TcpListener lis=new TcpListener(5000); //服务器监听
  lis.Start();//启动
  Socket sock=lis.AcceptSocket();//阻塞,直到有客户端连接
  
  NetworkStream networkStream = new NetworkStream(sock);//得到Socket中的流
  if (netStream.DataAvailable)   //如果客户端发送了消息
  {
     byte[] data = new byte[1024];   //定义一个字节数组,用来存放接收的数据
     int len = netStream.Read(data, 0, data.Length);  //从位置开始,读取到字节数组末尾
    string line = Encoding.Default.GetString(data, 0, len);  //把收到的字节转换为字符串
 }

 TcpClient client = new TcpClient();//客户端tcp对象
 client.Connect("127.0.0.1", 5000);//连接服务器
 NetworkStream myStream = client.GetStream();//得到网络流
                 
 byte[] data = Encoding.Default.GetBytes("Hi,你好");  //首先把输入的字符串消息转换为字节
 myStream .Write(data, 0, data.Length);  //向myStream 里写入数据
 myStream .Flush();  //刷新流中的数据
 myStream .Close();



五  StreamReader/StreamWriter类
     StreamReader/StreamWriter主要用来处理流数据。它们分别提供了高效的流读取/写入功能。
     读取与写入:

 StreamReader reader = new StreamReader("filePath");//初始化读取
 StreamWriter writer = new StreamWriter("filePath");//初始化写入
  
 string readStr=reader.ReadLine();//从流中读取一行
 string readAff = reader.ReadToEnd();//从流中读取全部
  
 writer.Write("Hi 你好");//写入内容
 writer.WriteLine("Hi 你好");//写入一行
 
 reader.Close();//关闭流
 writer.Close();



六  TextReader/TextWriter类

TextReader/TextWriter类主要用来处理流数据。它们分别提供了高效的文本流读取/写入功能。

读取与写入:

 TextReader textReader = new StringReader("Hi 你好");//初始化读取流
  TextWriter textWriter = new StringWriter();//初始化写入流
  
  char[] c=new char[4096];
  int chars = 0;
  while ((chars = textReader.Read(c, 0, 4096)) > 0)//把流中数据写入到字符数组中
  {
     textWriter.Write(c, 0, 4096);//从字符数组中读取流
  }
 
 string str= textWriter.ToString();//将流中数据写到字符串中
 textReader.Close();//关闭流
 textWriter.Close();


注意事项:


1.流使用后必须要关闭。


2.把流中数据加载到内存时要考虑内存溢出等问题。


############################################################


 .NET Framework 类库的System.IO 命名空间
      System.IO 命名空间包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。


      二 C#文件读写之FileStream详解
  

 (FileStream fs1 = File.Open("c:\\test.txt", FileMode.Open));

  //FileMode.Open 直接用FileStream类打开文件c:\\test.txt"。

   (FileStream fs2 = File.Open("c:\\test.txt", FileMode.Append, FileAccess.Write));

  //FileMode.Append,以追加的方式打开文件"c:\\test.txt",将某些内容写到"c:\\test.txt"里。

  (FileStream fs3 =File.Open("c:\\test.txt", FileMode.Truncate, FileAccess.ReadWrite, FileShare.Read)).

 // FileMode.Truncate的意思是将文件打开清空里面的内容后再对文件进行操作。

   FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);


  这个方法的意思是创建一个可以读写的文件,并且可以允许其他人读取文件的内容。


      三 C#基于流的输入输出
      C#基于流的输入输出.:Stream-通过C# I/O 系统与物理设备连接起来,也就是平时读写的硬盘等物理存贮设备.流/Stream的方法和属性有:
  

  Method/ Properties    //描述
    void Close()    //关闭流
    void Flush()    //清理流中的内容
    int ReadByte()   // 返回一个整数表示输入的字节数,如果没有数据返回-1
    int Read(byte[ ] buf,int offset, int numBytes)    
      //将numBytes个字节读入到byte[ ]的以offset为,起始位置,返回读入成功的字节数
    
    Long Seek(long offset,SeekOrigin origin) // 将当前位置定位到以origin为初始位置以后的offset处.
    void WriteByte(byte b)    //将单个字节写入到一个输出流.
    void Write(byte[ ] buf,int offset, int numBytes)    //写入byte[ ] buf中从offset开始的numBytes个字节.
    bool CanRead    //是否可读
    bool CanSeek   // 是否支持寻址
    bool CanWrite   // 是否可以写入数据
    long Length    //流的长度
    long Position    //流的当前位置.


  三. 流的继承结构
 

    Stream是一个很大类的,在读写文件的时候,可以通过不同的流进行专业的数据读写
    The FileMode and FileAccess的几条规则:
    Value    意义
    FileMode.Create    创建文件,之前存在同名的文件将被毁掉
    FileMode.CreateNew    创建新文件,这个文件之前不存在
    FileMode.Open    打开已经存在的文件
    FileMode.OpenOrCreate    打开文件如果存在,否则创建新文件
    FileMode.Truncate    打开以存在的文件,将它的内容清除掉
    FileMode.Append    以追加的形式将数据写入到文件的最后


  如果在打开文件的时候想限制文件访问权限,那么可以做如下的构造方法:
  FileStream(string filename, FileMode mode, FileAccess access);
                              文件名       文件模式       操作模式


  Access可以是以下当中的一个值:


  FileAccess.Read/  FileAccess.Write/  FileAccess.ReadWrite;


  FileStreamfs=new FileStream(“c:\\tab.txt”,FileMode.OpenOrCreate,FileAccess.Read);
--------------------- 
作者:tuhongwu25 
来源:CSDN 
原文:https://blog.csdn.net/tusofthappy/article/details/79648645 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
软件介绍: ArrayNetworksL3Setu是移动代理点客户端软件,也就是常说的那个红A。需要安装这个软件后才能登陆。BOSS 客户端更新说明为了解决现有BOSS系统BUG,现在需要升级各代办点终端的SSL 的插件,具体插件步骤如下:1.将附件中名称为:“ArrayNetworksL3OnlyWebSetup.zip”的安装包拷贝到代办终端上。 2.在代办终端上解压该文件3.点击“setup.exe”4.一步步安装首先remove现有的插件。点击“next”,点击“finish”,再点击“setup.exe”,点击“finish”完成安装。完成后开始使用,打开IE浏览器。输入移动 IP地址。IE版本可能会出现,点击“允许”,当右下角出现“A” 上面出现8.4.6.80确认为新的插件版本。出现红A,没有任何报错就示安装正常。-----------------------------------------------------------------------------------------------------如果安装有问题或者不能正常访问,请单独安装客户端。安装的文件名称ArrayNetworksL3SetupX32.zip,ArrayNetworksL3SetupX64.zip请对应系统的版本安装1查看自己的系统的版本,32位,64位2.“计算机”-->“属性”查看自己的是32位的还是64位的操作系统。请对应版本安装。4.安装客户端软件的步骤,首先解压文件。点击 “setup.exe”安装完成。打开IE登陆SSL 如重启失败请重置浏览器的高级设置。点击---“还远高级设置”---“确定”再次登陆
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值