文本文件导入,得到数据集

本文介绍了一种将文本文件中的数据导入到数据集的方法。通过使用StreamReader读取指定编码(如gb2312)的文本文件内容,并按行解析数据,将其拆分为字符串数组,然后填充到DataTable中。每读取一行,就创建一个新的DataRow并添加到DataTable中。

 

/// <summary>
        
/// 从文本文件导入
        
/// </summary>
        
/// <param name="Filename">文件路径</param>
        
/// <param name="dtData">数据</param>
        
/// <returns>数据集</returns>

        public DataTable TxtToDataSet(string Filename, ref DataTable dtData)
        
{
            DataSet ds 
= new DataSet();
            
try
            
{
                StreamReader sr 
= new StreamReader(Filename, Encoding.GetEncoding("gb2312"));
                
//sr.CurrentEncoding.

                String line;
                DataRow myRow;
                
while ((line = sr.ReadLine()) != null)
                
{
                    myRow 
= dtData.NewRow();

                    
string[] strs = line.Split(',');
                    
int i = 0, j = 0, linelength = strs.Length;

                    
foreach (string s in strs)
                    
{
                        myRow[j
++= s;
                        
if (j == linelength)
                        
{
                            j 
= 0;
                            i
++;
                        }

                    }


                    dtData.Rows.Add(myRow);
                }


                
//关闭删除
                sr.Close();
                File.Delete(Filename);

            }

            
catch (Exception ex)
            
{
                
throw ex;
            }


            
return dtData;

        }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Actionmr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值