-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExportXml.cs
118 lines (101 loc) · 4.55 KB
/
ExportXml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using Speed.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Speed.Common;
using System.Text;
using System.ComponentModel;
namespace ExportDbToFile
{
public class ExportXml
{
StreamWriter writerOk;
StreamWriter writerError;
public int Export(Database db, BackgroundWorker worker, string dir, string select, bool columnFileNames, bool exportNulls, Label lblMessage, string extension, out int count)
{
count = 0;
extension = extension.Replace(".", "");
using (writerOk = new StreamWriter(Path.Combine(dir, "_Export_OK.txt"), false))
{
using (writerError = new StreamWriter(Path.Combine(dir, "_Export_Error.txt"), false))
{
lblMessage.Text = "Consultando ...";
lblMessage.Update();
select = select.Trim();
if (select.EndsWith(";"))
select = select.Substring(0, select.Length - 1);
using (var reader = db.ExecuteReader(select, 0))
{
while (reader.Read())
{
if (worker.CancellationPending)
{
return count;
}
count++;
try
{
if (count % 10 == 0)
{
lblMessage.Text = string.Format("Processados {0} registros", count);
lblMessage.Update();
}
string fileName = null;
object value = null;
for (int i = 0; i < reader.FieldCount; i += (columnFileNames ? 2 : 1))
{
if (columnFileNames)
{
fileName = reader.GetValue(i) as string;
if (fileName == null)
fileName = reader.GetName(i) + "_" + count;
value = reader.GetValue(i + 1);
}
else
{
fileName = reader.GetName(i) + "_" + count;
value = reader.GetValue(i);
}
if (!exportNulls && (value == DBNull.Value || value == null))
{
continue;
}
fileName = Path.Combine(dir, Speed.IO.FileTools.ToValidPath(fileName));
if (!string.IsNullOrWhiteSpace(extension) && Path.GetExtension(fileName).Replace(".", "").ToLower() != extension)
{
fileName += "." + extension;
}
if (value is byte[])
{
File.WriteAllBytes(fileName, (byte[])value);
}
else
{
File.WriteAllText(fileName, value.ToString(), UTF8Encoding.UTF8);
}
}
}
catch (Exception ex)
{
LogError(ex.Message + "\r\n" + ex.StackTrace);
}
}
lblMessage.Text = string.Format("Processados {0} registros", count);
lblMessage.Update();
}
}
}
return count;
}
void LogOk(string message)
{
writerOk.WriteLine(message);
}
void LogError(string message)
{
writerError.WriteLine(message);
}
}
}