winform如何用IO文件流保存数据库数据及表

winform如何用IO文件流保存数据库数据及表,第1张

方法一:

private string connStr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString

/// <summary>

/姿兄// 用insert方法从文本文件中批量导入到数据库表中

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void btnInsert_Click(object sender, RoutedEventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog()

ofd.Filter = "文本文档|*.txt"

//如果用户没有选择文件并确定则直接返回

if (ofd.ShowDialog() != true)

{

return

}

//获得文件名包括路径

string fileName = ofd.FileName

try

{

//定义一个开始时间

DateTime startTime = DateTime.Now

//厅册型因为文件比较大,所有使用StreamReader的效率要比使用File.ReadLines高

using (StreamReader sr = new StreamReader(fileName, Encoding.Default))

{

using (SqlConnection conn = new SqlConnection(connStr))

{

conn.Open()

using (SqlCommand cmd = conn.CreateCommand())

{

while (!sr.EndOfStream)

{

string readStr = sr.ReadLine()//读取一行数据

if (readStr.StartsWith("1"))//去掉标题行

{

string[] strs = readStr.Split(new char[] { '\t', '"' }, StringSplitOptions.RemoveEmptyEntries)//将读取的字符串按"制表符/t“和””“分扮猜割成数组

string startNum = strs[0]

string numArea = strs[1]

string numType = strs[2]

cmd.CommandText = "insert into T_PhoneInfo(FStartNum,FNumArea,FNumType) values(@startNum,@numArea,@numType)"

cmd.Parameters.Clear()//清除上一次的参数

cmd.Parameters.Add(new SqlParameter("@startNum", startNum))

cmd.Parameters.Add(new SqlParameter("@numArea", numArea))

cmd.Parameters.Add(new SqlParameter("@numType", numType))

cmd.ExecuteNonQuery()

}

}

}

}

}

//结束时间-开始时间=总共花费的时间

TimeSpan ts = DateTime.Now - startTime

MessageBox.Show("导入数据成功!共花费时间:" + ts.ToString())

}

catch (IOException ex)

{

MessageBox.Show(ex.Message)

}

catch (Exception ex)

{

MessageBox.Show(ex.Message)

}

}

方法二:

private void btnSqlBulkCopy_Click(object sender, RoutedEventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog()

ofd.Filter = "文本文档|*.txt"

//如果用户没有选择文件并确定则直接返回

if (ofd.ShowDialog() != true)

{

return

}

//获得文件名包括路径

string fileName = ofd.FileName

try

{

//定义一个开始时间

DateTime startTime = DateTime.Now

//创建内存临时数据表来存储从文本文件中读取出来的数据

using (DataTable table = new DataTable())

{

//为数据表创建相对应的数据列

table.Columns.Add("startNum")

table.Columns.Add("numArea")

table.Columns.Add("numType")

//因为文件比较大,所有使用StreamReader的效率要比使用File.ReadLines高

using (StreamReader sr = new StreamReader(fileName, Encoding.Default))

{

while (!sr.EndOfStream)

{

DataRow dr = table.NewRow()//创建数据行

string readStr = sr.ReadLine()//读取一行数据

if (readStr.StartsWith("1"))//去掉标题行

{

string[] strs = readStr.Split(new char[] { '\t', '"' }, StringSplitOptions.RemoveEmptyEntries)//将读取的字符串按"制表符/t“和””“分割成数组

string startNum = strs[0]

string numArea = strs[1]

string numType = strs[2]

//往对应的 行中添加数据

dr["startNum"] = startNum

dr["numArea"] = numArea

dr["numType"] = numType

table.Rows.Add(dr)//将创建的数据行添加到table中

}

}

}

SqlBulkCopy bulkCopy = new SqlBulkCopy(connStr)

bulkCopy.DestinationTableName = "T_PhoneInfo"//设置数据库中对象的表名

//设置数据表table和数据库中表的列对应关系

bulkCopy.ColumnMappings.Add("startNum", "FStartNum")

bulkCopy.ColumnMappings.Add("numArea", "FNumArea")

bulkCopy.ColumnMappings.Add("numType", "FNumType")

bulkCopy.WriteToServer(table)//将数据表table复制到数据库中

TimeSpan ts = DateTime.Now - startTime

MessageBox.Show("共导入" +table.Rows.Count+ "条数据,总共花费时间:" + ts.ToString())

}

}

catch (IOException ex)

{

MessageBox.Show(ex.Message)

}

catch (Exception ex)

{

MessageBox.Show(ex.Message)

}

}

if(sr!=null)

{

if (openFileDialog1.ShowDialog() == DialogResult.OK)

{

sr = new StreamReader(openFileDialog1.FileName, Encoding.Unicode)

}

这样空尺就可以碰毕了斗吵高

C#实现访问网络共享文件夹则搜,使用 WNetAddConnection2A 和 WNetCancelConnection2A。桐启

在目标服务器建立共享局盯如文件夹,建立访问账号test

public enum ERROR_ID

{

ERROR_SUCCESS = 0, // Success

ERROR_BUSY = 170,

ERROR_MORE_DATA = 234,

ERROR_NO_BROWSER_SERVERS_FOUND = 6118,

ERROR_INVALID_LEVEL = 124,

ERROR_ACCESS_DENIED = 5,

ERROR_INVALID_PASSWORD = 86,

ERROR_INVALID_PARAMETER = 87,

ERROR_BAD_DEV_TYPE = 66,

ERROR_NOT_ENOUGH_MEMORY = 8,

ERROR_NETWORK_BUSY = 54,

ERROR_BAD_NETPATH = 53,

ERROR_NO_NETWORK = 1222,

ERROR_INVALID_HANDLE_STATE = 1609,

ERROR_EXTENDED_ERROR = 1208,

ERROR_DEVICE_ALREADY_REMEMBERED = 1202,

ERROR_NO_NET_OR_BAD_PATH = 1203

}

public enum RESOURCE_SCOPE

{

RESOURCE_CONNECTED = 1,

RESOURCE_GLOBALNET = 2,

RESOURCE_REMEMBERED = 3,

RESOURCE_RECENT = 4,

RESOURCE_CONTEXT = 5

}

public enum RESOURCE_TYPE

{

RESOURCETYPE_ANY = 0,

RESOURCETYPE_DISK = 1,

RESOURCETYPE_PRINT = 2,

RESOURCETYPE_RESERVED = 8,

}

public enum RESOURCE_USAGE

{

RESOURCEUSAGE_CONNECTABLE = 1,

RESOURCEUSAGE_CONTAINER = 2,

RESOURCEUSAGE_NOLOCALDEVICE = 4,

RESOURCEUSAGE_SIBLING = 8,

RESOURCEUSAGE_ATTACHED = 16,

RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),

}

public enum RESOURCE_DISPLAYTYPE

{

RESOURCEDISPLAYTYPE_GENERIC = 0,

RESOURCEDISPLAYTYPE_DOMAIN = 1,

RESOURCEDISPLAYTYPE_SERVER = 2,

RESOURCEDISPLAYTYPE_SHARE = 3,

RESOURCEDISPLAYTYPE_FILE = 4,

RESOURCEDISPLAYTYPE_GROUP = 5,

RESOURCEDISPLAYTYPE_NETWORK = 6,

RESOURCEDISPLAYTYPE_ROOT = 7,

RESOURCEDISPLAYTYPE_SHAREADMIN = 8,

RESOURCEDISPLAYTYPE_DIRECTORY = 9,

RESOURCEDISPLAYTYPE_TREE = 10,

RESOURCEDISPLAYTYPE_NDSCONTAINER = 11

}

[StructLayout(LayoutKind.Sequential)]

public struct NETRESOURCE

{

public RESOURCE_SCOPE dwScope

public RESOURCE_TYPE dwType

public RESOURCE_DISPLAYTYPE dwDisplayType

public RESOURCE_USAGE dwUsage

[MarshalAs(UnmanagedType.LPStr)]

public string lpLocalName

[MarshalAs(UnmanagedType.LPStr)]

public string lpRemoteName

[MarshalAs(UnmanagedType.LPStr)]

public string lpComment

[MarshalAs(UnmanagedType.LPStr)]

public string lpProvider

}

public class NetworkConnection

{

[DllImport("mpr.dll")]

public static extern int WNetAddConnection2A (NETRESOURCE[] lpNetResource, string lpPassword, string lpUserName, int dwFlags)

[DllImport("mpr.dll")]

public static extern int WNetCancelConnection2A (string sharename, int dwFlags, int fForce)

public static int Connect (string remotePath, string localPath, string username, string password)

{

NETRESOURCE[] share_driver = new NETRESOURCE[1]

share_driver[0].dwScope = RESOURCE_SCOPE.RESOURCE_GLOBALNET

share_driver[0].dwType = RESOURCE_TYPE.RESOURCETYPE_DISK

share_driver[0].dwDisplayType = RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_SHARE

share_driver[0].dwUsage = RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE

share_driver[0].lpLocalName = localPath

share_driver[0].lpRemoteName = remotePath

Disconnect(localPath)

int ret = WNetAddConnection2A(share_driver, password, username, 1)

return ret

}

public static int Disconnect (string localpath)

{

return WNetCancelConnection2A(localpath, 1, 1)

}

调用方式:

public static void TestNetWorkConnection()

{

string localpath = "X:"

//int status = NetworkConnection.Connect(@"\\192.168.0.2\test", localpath, @"test", "test")

int status = NetworkConnection.Connect("\\\\192.168.0.2\\test", localpath, @"test", "test")

if (status == (int)ERROR_ID.ERROR_SUCCESS)

{

FileStream fs = new FileStream(localpath + @"\\123.txt", FileMode.OpenOrCreate)

using (StreamWriter stream = new StreamWriter(fs))

{

stream.WriteLine("你好呀,成功了")

stream.Flush()

stream.Close()

}

fs.Close()

}

else

{

Console.WriteLine(status)

}

NetworkConnection.Disconnect(localpath)

}

下载的时候请是用文件流··

如果服务器设置了关闭ping的方法。

就很难实现了·

参考:

http://support.microsoft.com/kb/173011

http://support.microsoft.com/kb/842789


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12120269.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存