今天有空,把C#常用的功能总结一下,希望对您有用。(适用于.NET Framework 4.5)
|
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 |
using
System.IO;using
System.Text;using
System.Xml;using
System.Xml.Serialization;public
static
string
Serialize<T>(T t, string
nameSpacePri, string
nameSpace){ try { var
myNamespaces = new
XmlSerializerNamespaces(); myNamespaces.Add(nameSpacePri, nameSpace); var
xs = new
XmlSerializer(t.GetType()); using
(var
memoryStream = new
MemoryStream()) { var
settings = new
XmlWriterSettings() { Encoding = Encoding.UTF8 }; using
(var
writer = XmlWriter.Create(memoryStream, settings)) { xs.Serialize(writer, t, myNamespaces); } return
Encoding.UTF8.GetString(memoryStream.ToArray()); } } catch
(System.Exception) { return
null; } } |
|
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 |
using
System.IO;using
System.Text;using
System.Xml;using
System.Xml.Serialization;public
sealed
class
XmlSerilizer{ public
static
T Deserialize<T>(string
input) { try { var
xs = new
XmlSerializer(typeof
(T)); using
(var
reader = new
StringReader(input)) { var
namespaceReader = new
NamespaceIgnorantXmlTextReader(reader); return
(T) xs.Deserialize(namespaceReader); } } catch
(System.Exception e) { return
default(T); } }}//忽略xml里面的namespacepublic
class
NamespaceIgnorantXmlTextReader : XmlTextReader{ /// <summary> /// Initializes a new instance of the <see cref="NamespaceIgnorantXmlTextReader"/> class. /// </summary> /// <param name="reader">The reader.</param> public
NamespaceIgnorantXmlTextReader(System.IO.TextReader reader) : base(reader) { } /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned. /// </summary> /// <value>The namespace URI.</value> /// <returns>The namespace URI of the current node; otherwise an empty string.</returns> public
override
string
NamespaceURI { get
{ return
""; } }} |
以上要注意xml的root,实体类要这样写:
|
1
2
3
4
5
6
7
8
9
10
11
12
13 |
[Serializable][XmlRoot(ElementName = "yourXmlRootName", DataType = "string", IsNullable = true)]public
class
Model{ [XmlElement(ElementName = "merchant", IsNullable = true)] public
string
merchant { get; set; } [XmlElement(ElementName = "address", IsNullable = false)] public
string
address{ get; set; } [XmlElement(ElementName = "status", IsNullable = false)] public
string
status { get; set; }} |
|
1 |
return
Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString); |
|
1 |
string
output = Newtonsoft.Json.JsonConvert.SerializeObject(product); |
|
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 |
using
System.Text;using
System.Threading;using
System.Threading.Tasks;using
System;using
System.IO;using
System.Reflection;using
System.Security.Cryptography; public
static
string
GetApplicationDataPath(){ try { var
asm = Assembly.GetEntryAssembly(); var
attrs = asm.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); var
company = (AssemblyCompanyAttribute)attrs[0]; attrs = asm.GetCustomAttributes(typeof(AssemblyTrademarkAttribute), false); var
tradeMark = (AssemblyTrademarkAttribute)attrs[0]; var
pathTemp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), company.Company); pathTemp = Path.Combine(pathTemp, tradeMark.Trademark); pathTemp = Path.Combine(pathTemp, asm.GetName().Name); return
pathTemp; } catch
(System.Exception) { return
string.Empty; }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13 |
using
System.Text;using
System.Threading;using
System.Threading.Tasks;using
System;using
System.IO;using
System.Reflection;using
System.Security.Cryptography;public
static
void
Empty(this
DirectoryInfo directory){ foreach
(FileInfo file in
directory.GetFiles()) file.Delete(); foreach
(DirectoryInfo subDirectory in
directory.GetDirectories()) subDirectory.Delete(true);} |
|
1
2
3
4
5
6
7
8
9 |
using
System.Security.Cryptography;public
static
string
CalculateFileSha(byte[] buffer){ using
(var
cryptoProvider = new
SHA1CryptoServiceProvider()) { return
Convert.ToBase64String(cryptoProvider.ComputeHash(buffer)); }} |
|
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 |
using
System.Text;using
System.Threading;using
System.Threading.Tasks;using
System;using
System.IO;using
System.Reflection;using
System.Security.Cryptography;public
static
void
WriteFileAsync(string
content, string
fileName, bool
append){ if
(String.IsNullOrEmpty(content)||string.IsNullOrEmpty(fileName)) return; Task.Factory.StartNew(() => { try { using
(var
writer = new
StreamWriter(fileName, append, Encoding.UTF8)) { writer.AutoFlush = true; writer.WriteLine(content); writer.Close(); } } catch
(System.Exception) { } });} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
public
static
void
WaitForFile(string
fullPath){ while
(true) { try { using
(var
stream = new
StreamReader(fullPath)) { break; } } catch { Thread.Sleep(100); } }} |
|
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 |
using
System.Linq;using
System.Xml;using
System.Xml.Linq;namespace
myCompany{ public
sealed
class
XmlUtility { public
static
XDocument DocumentToXDocument(XmlDocument doc) { return
XDocument.Load(new
XmlNodeReader(doc)); } public
static
XmlDocument XDocumentToXmlDocument(XDocument doc) { var
xmlDocument = new
XmlDocument(); using
(var
xmlReader = doc.CreateReader()) { xmlDocument.Load(xmlReader); } return
xmlDocument; } public
static
XDocument XElementToXDocument(XElement element) { return
new
XDocument(element); } public
static
string
RemoveAllNamespaces(string
xmlDocument) { XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return
xmlDocumentWithoutNs.ToString(); } public
static
XElement RemoveAllNamespaces(XElement xmlDocument) { if
(!xmlDocument.HasElements) { var
xElement = new
XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach
(var
attribute in
xmlDocument.Attributes()) xElement.Add(attribute); return
xElement; } return
new
XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); } public
static
XDocument RemoveNamespaces(XDocument xmlDocument, string
namespaces) { return
XDocument.Parse(xmlDocument.ToString().Replace(namespaces, "")); } }} |
|
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 |
using
System;using
System.Xml.Linq;using
System.Xml.Xsl;using
ETMS.MCC.Logging;using
ETMS.MCC.Utility;namespace
myCompany{ public
class
Converter { [ThreadStatic] private
static
XslCompiledTransform xslTransformer; public
XDocument XsltTransform(XDocument inputDocument) { System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); return
Transform(Utility.Constants.Configuration.ParameterXsltFile, inputDocument); } public
XDocument XsltTransform(string
xsltFilename, XDocument inputDocument) { return
Transform(xsltFilename, inputDocument); } private
XDocument Transform(string
xsltFilename, XDocument inputDocument) { try { if
(xslTransformer == null) { xslTransformer = new
XslCompiledTransform(); xslTransformer.Load(xsltFilename); } var
result = new
XDocument(); using
(var
xw = result.CreateWriter()) { xslTransformer.Transform(XmlUtility.XDocumentToXmlDocument(inputDocument), null, xw); xw.Close(); return
result; } } catch
(Exception e) { return
null; } } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
using
System;using
System.Collections.Generic;using
System.Threading;using
System.Threading.Tasks;public
static
async Task BulkExecute<T>(int
maxConcurrency, IEnumerable<T> items, Func<T, Task> createTask){ using
(var
sem = new
SemaphoreSlim(maxConcurrency)) { var
tasks = new
List<Task>(); foreach
(var
item in
items) { await sem.WaitAsync(); var
task = createTask(item).ContinueWith(t => sem.Release()); tasks.Add(task); } await Task.WhenAll(tasks); }} |
|
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 |
using
System;using
System.Collections.Concurrent;using
System.Collections.Generic;using
System.Threading;using
System.Threading.Tasks;using
System.Timers;namespace
myCompany{ public
abstract
class
AbstractProcessingQueue<T> : ConcurrentQueue<T> where
T : class { protected
int
_numberLimit; protected
int
_timeLimit; protected
System.Timers.Timer _timer; protected
int
_onPublishExecuted; protected
ReaderWriterLockSlim _locker; protected
AbstractProcessingQueue() { } protected
AbstractProcessingQueue(int
numberLimit, int
timeLimit) { Init(numberLimit, timeLimit); } public
event
Action<List<T>> OnPublish = delegate
{ }; public
virtual
new
void
Enqueue(T item) { base.Enqueue(item); if
(_numberLimit > 0 && Count >= _numberLimit) { Logger.GlobalWrite(string.Format("Processing queue number limit: {0}", _numberLimit), LogMessageCategory.Warning); Publish(); } } private
void
Init(int
capLimit, int
timeLimit) { _numberLimit = capLimit; _timeLimit = timeLimit; _locker = new
ReaderWriterLockSlim(); InitTimer(); } protected
virtual
void
InitTimer() { if
(_timeLimit < 0) return; _timer = new
System.Timers.Timer {AutoReset = false, Interval = _timeLimit*1000}; _timer.Elapsed += new
ElapsedEventHandler((s, e) => { Logger.GlobalWrite(string.Format("Processing queue time limit: {0}", _timeLimit), LogMessageCategory.Warning); Publish(); }); _timer.Start(); } protected
virtual
void
Publish() { var
task = new
Task(() => { var
itemsToLog = new
List<T>(); try { if
(IsPublishing()) return; StartPublishing(); T item; while
(TryDequeue(out
item)) { itemsToLog.Add(item); } } catch
(ThreadAbortException tex) { } catch
(Exception ex) { } finally { OnPublish(itemsToLog); CompletePublishing(); } }); task.Start(); } private
bool
IsPublishing() { return
(Interlocked.CompareExchange(ref
_onPublishExecuted, 1, 0) > 0); } private
void
StartPublishing() { if
(_timer != null) _timer.Stop(); } private
void
CompletePublishing() { if
(_timer != null) _timer.Start(); Interlocked.Decrement(ref
_onPublishExecuted); } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
using
System;namespace
myCompany{ public
sealed
class
Singleton { static
readonly
Singleton Instance = new
Singleton(); private
Singleton() { } public
static
Singleton GetInstance() { return
Instance; } }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
using
System;using
System.Web;public
static
MediaTypes GetMediaType(string
contentTypeHeader){ if
(String.IsNullOrEmpty(contentTypeHeader)) return
MediaTypes.UNKNOWN; if
(contentTypeHeader.Contains("text/plain")) return
MediaTypes.TEXT; if
(contentTypeHeader.Contains("application/json")) return
MediaTypes.JSON; if
(contentTypeHeader.Contains("html")) return
MediaTypes.HTML; if
(contentTypeHeader.Contains("application/xml")) return
MediaTypes.XML; return
MediaTypes.UNKNOWN;} |
|
1
2
3
4
5
6
7
8 |
using
System;using
System.Web;public
static
string
ParseText(string
bodyText, string
key){ return
HttpUtility.ParseQueryString(myUri.Query).Get(key);} |
|
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 |
using
System.Xml;using
System.Xml.Linq; public
long
ParseXmlString(string
messageBody){ try { var
xm = new
XmlDocument(); xm.LoadXml(messageBody); using
(var
reader = new
XmlNodeReader(xm)) { var
Id = ""; var
doc = XDocument.Load(reader); var
ele = doc.Document.Element("root1").Element("elementName"); if
(ele != null) Id = ele.Value; long
id; if
(!Int64.TryParse(Id, out
id)) { return
-1; } return
id; } } catch
(Exception e) { return
-1; }} |
|
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 |
using
ICSharpCode.SharpZipLib.Core;using
ICSharpCode.SharpZipLib.Zip;using
System.IO; public
byte[] ZipFiles(IEnumerable<byte[]> contents){ try { using
(var
compressedFileStream = new
MemoryStream()) { using
(var
zipStream = new
ZipOutputStream(compressedFileStream)) { zipStream.SetLevel(9); foreach
(var
p in
contents) { using
(var
srcStream = new
MemoryStream(p)) { var
entry = new
ZipEntry("newname"); zipStream.PutNextEntry(entry); StreamUtils.Copy(srcStream, zipStream, new
byte[4096]); zipStream.CloseEntry(); } } zipStream.IsStreamOwner = false; zipStream.Close(); compressedFileStream.Position = 0; return
compressedFileStream.ToArray(); } } } catch
(Exception e) { return
null; }} |
19. …请补充
原文:http://www.cnblogs.com/Mainz/p/3531097.html