In this case, the dataobject is a memory stream. Here are code snippets that allow you to get/set CSV values from/to the clipboard in a manner compatible with Excel.
[C#]private void GetCSVFromClipBoard_Click(object sender, System.EventArgs e)
{
IDataObject o = Clipboard.GetDataObject();
if(o.GetDataPresent(DataFormats.CommaSeparatedValue))
{
StreamReader sr = new StreamReader((Stream) o.GetData(DataFormats.CommaSeparatedValue));
string s = sr.ReadToEnd();
sr.Close();
Console.WriteLine(s);
}
}
private void CopyCSVToClipBoard_Click(object sender, System.EventArgs e)
{
String csv = '1,2,3' + Environment.NewLine + '6,8,3';
byte[] blob = System.Text.Encoding.UTF8.GetBytes(csv);
MemoryStream s = new MemoryStream(blob);
DataObject data = new DataObject();
data.SetData(DataFormats.CommaSeparatedValue, s);
Clipboard.SetDataObject(data, true);
}
[VB.NET]
Private Sub GetCSVFromClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim o As IDataObject = Clipboard.GetDataObject()
If Not o Is Nothing Then
If (o.GetDataPresent(DataFormats.CommaSeparatedValue)) Then
Dim sr AsNew StreamReader(CType(o.GetData(DataFormats.CommaSeparatedValue), Stream))
Dim s As String = sr.ReadToEnd()
sr.Close()
Console.WriteLine(s)
End If
End If
End Sub ’GetCSVFromClipBoard_Click
Private Sub CopyCSVToClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim csv As String = '1,2,3' + Environment.NewLine + '6,8,3'
Dim blob As Byte() = System.Text.Encoding.UTF8.GetBytes(csv)
Dim s AsNew MemoryStream(blob)
Dim data AsNew DataObject()
data.SetData(DataFormats.CommaSeparatedValue, s)
Clipboard.SetDataObject(data, True)
End Sub ’CopyCSVToClipBoard_Click
.NET has excellent support for Regular Expressions. Get the excellent ‘Regular Expressions with .NET ‘, e-book by Dan Appleman. It has all that you need to get started.
Regular expressions really make string processing easier.
There are expressions that you can find on the web for everything from validating dates to phone numbers.
Use the StringBuilder class to concatenate strings. This class reuses memory. If you add string members to concatenate them, there is extra overhead as new memory is allocated for the new string. If you do a series of concatenations using the strings (instead of StringBuilder objects) in a loop, you continually get new strings allocated. StringBuilder objects allocate a buffer, and reuse this buffer in its work, only allocating new space when the initial buffer is consumed. Here is a typical use case.
VB.NET has a IsNumeric method that you can use to recognize a Short, Integer, Long, Decimal or Single numeric type. From C#, you can use try/catch to look for a particular numeric type.
//long for a Single
Single num;
try
{
num = Single.Parse(someString);
}
catch (Exception e)
{
// if this is hit, someString is not a Single
}