How to validate CSV in C#? - c#

Is there a built-in method in .NET that validates csv files/strings?
I would prefer something like this online csv validator but in C#. I have done some research but all I have found are examples of people writing the code themselves (examples were all written a few years ago and might be outdated).
POC:
bool validCSV = CoolCSV_ValidatorFunction(string csv/filePath);

There is! For some reason it's buried in the VB namespace, but it's part of the .NET Framework, you just need to add a reference to the Microsoft.VisualBasic assembly. The type you're looking for is TextFieldParser.
Here is an example of how to validate your file:
using Microsoft.VisualBasic.FileIO;
...
var path = #"C:\YourFile.csv";
using (var parser = new TextFieldParser(path))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
string[] line;
while (!parser.EndOfData)
{
try
{
line = parser.ReadFields();
}
catch (MalformedLineException ex)
{
// log ex.Message
}
}
}

The best CSV reader I've found is this one from Lumenworks:
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
Very fast, very full-featured. Recommended.

That CSV Parser also seems promising (Not built-in, though):
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
Related thread:
CSV Parsing Options with .NET

Related

How to convert ppt to HTML in C#?

In my website, admin can upload a PPT & on submission, I am in need to convert to html.
I was using OpenXML library for the Word document. I thought the same lib can be used for PPT also. But not finding the method for the same.
namespace OpenXML_Sample
{
class Program
{
static void Main(string[] args)
{
ExportHTML.GenerateHTML(#"D:\test.pptx");
Console.ReadKey();
}
}
public class ExportHTML
{
public static XElement GenerateHTML(string filePath)
{
try
{
byte[] byteArray = File.ReadAllBytes(filePath);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
using (PresentationDocument pptDoc=
PresentationDocument.Open(memoryStream, true))
{
HtmlConverterSettings settings = new HtmlConverterSettings()
{
PageTitle = "My Page Title"
};
//not accepting pptDoc as parameter,throws compile time error.
XElement xHtml = HtmlConverter.ConvertToHtml(pptDoc, settings);
var html = xHtml.ToString();
File.WriteAllText(#"D:\sample.html", html,Encoding.UTF8);
return xHtml;
}
}
}
catch (Exception ex)
{
throw new FileLoadException(ex.InnerException.Message.ToString());
}
}
}
}
How do I pass the ppt document to the method to generate the html document of the uploaded ppt file.
Would welcome for any other(free) api as well.
I have used the Aspose library before and I believe it supports what you are wanting to achieve.
A quick search on their forums revealed this post which might suit your needs;
web,
I like to share that Aspose.Slides for .NET supports exporting presentation file to HTML and you don't even need to install MS Office for this on your machine. All you need to do is to use the appropriate functionality in API. Please visit this documentation link for your kind reference. If you still have an issue then please contact us in Aspose.Slides support forum.
I am working as Support developer/ Evangelist at Aspose.
There are some examples of converting in C# with iSpring Platform http://www.ispringsolutions.com/ispring-platform. It isn’t tailored for a certain programming language, but it’s easy to use it with C#. First of all, there are some examples, and secondly, there’s a Code Builder app, so you can set the necessary conversion configuration and use the generated C# code in your app.

C# CsvHelper - Missing CsvReader.cs

I am using CsvHelper to read a .CSV file into an html table. I am using .NET MVC 4 and CsvReader 2.13.2.0. I have tried different versions of CsvHelper and am still getting the same error on this line:
var csv = new CsvReader(new StreamReader(path));
Error:
I've looked in the CsvHelper folder and there is just a .dll, debug database, and an XML document. Does anybody know why this file does not exist or if I am using a depreciated CsvHelper method or something. Thanks!
I know this doesn't directly answer your question but I would look into LinqToCSV (you can find it on Nuget). With it you can use it to serialize a csv file into an object and use linq to iterate over it. It's very easy to use and since it's a package you won't need to worry about the dll management or the code being deprecated. I've used it in the past, I dont remember the exact syntax but loading the file is something like this:
var cc = new CsvContext();
cc.Read<YourModel>(filePath);
That will read the csv file into your C# object. Then you can just use it like any other object.
I had the same problem. But I forgot surrounding it with a try-/catch to see the root exception :-). Simple!
try
{
var csv = new CsvReader(new StreamReader(path));
}
catch (UnauthorizedAccessException e)
{
//handle it
}
catch (System.Exception e)
{
//handle it
}

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I have to use StringBuilder instead of a List of strings because of being stuck with .NET 1.1 for this project.
I want to write a series of debug messages I've written to a file to study at my leisure, as there is too much to see on the screen (the MessageBox doesn't have scrollbars). Some of the easy ways to write a file don't seem to be available in .NET 1.1. I also don't have access to Environment.Newline to cleanly separate the lines I append (AppendLine is not available in this archaic version of StringBuilder, either).
What is the easiest way in .NET 1.1 (C#) to write out the contents of the StringBuilder to a file? There is no "C" drive on the handheld device, so I reckon I will have to write it to "\hereIAm.txt" or something.
You still have access to StreamWriter:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText method.
System.IO.File.WriteAllText(#"C:\TextFile.txt", stringBuilder.ToString());
I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.
In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.
System.IO.File.WriteAllText(#"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());
No need for a StringBuilder:
string path = #"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write Method (String) (.NET Framework 1.1)
Writing Text to a File (.NET Framework 1.1)
StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:
StringBuilder sb = new StringBuilder();
sb.Append(......);
StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
sw.Write(sb.ToString());
sw.Close();
Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.
If you need to write line by line from string builder
StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");
using (var sw = new StreamWriter(#"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
If you need to write all text as single line from string builder
StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");
using (var sw = new StreamWriter(#"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}

Programmatically reading VS .coveragexml file in C#

So I have some code that can read the methods out of a .coverage file...
using (CoverageInfo info = CoverageInfo.CreateFromFile(this.myCoverageFile))
{
CoverageDS ds = info.BuildDataSet();
foreach (ICoverageModule coverageModule in info.Modules)
{
CodeModule currentModule = new CodeModule(coverageModule.Name);
byte[] coverageBuffer = coverageModule.GetCoverageBuffer(null);
using (ISymbolReader reader = coverageModule.Symbols.CreateReader())
{
Method currentMethod;
while (reader.GetNextMethod(out currentMethod, coverageBuffer))
{
if (currentMethod != null)
{
currentModule.Methods.Add(currentMethod);
}
}
}
returnModules.Add(currentModule);
}
}
... but I want to be able to read .coverage files that have been exported to xml too. The reason for this is that .coverage files require the source dlls be in the exact location they were when code coverage was measured, which doesn't work for me.
When I try to load a coveragexml file using CreateFromFile(string) I get the following exception.
Microsoft.VisualStudio.Coverage.Analysis.InvalidCoverageFileException
was unhandled Message=Coverage file
"unittestcoverage.coveragexml" is
invalid or corrupt.
The coveragexml file opens in Visual Studio just fine, so I don't believe there's any issue with the file's format.
I know that CoverageDS can import an xml file, but the API is less than intuitive and the only example I can find of its use is...
using(CoverageInfo info = CoverageInfo.CreateFromFile(fileString))
{
CoverageDS data = info.BuildDataSet();
data.ExportXml(xmlFile);
}
...which tells me nothing about how to actually read the coverage data from that file.
Does someone know how to process code coverage data from a .coveragexml file?
Probably the best introduction to manipulating code coverage information programmatically is available here and also in the linked ms_joc blog.
I'm pretty sure you can use 'CreateInfoFromFile' with either the .coverage file or the XML file you exported in the sample above.
UPDATE:
CreateInfoFromFile throws an exception if the coveragexml is passed as the argument. Here is an alternative:
CoverageDS dataSet = new CoverageDS();
dataSet.ImportXml(#"c:\temp\test.coveragexml");
foreach (CoverageDSPriv.ModuleRow module in dataSet.Module)
{
Console.WriteLine(String.Format("{0} Covered: {1} Not Covered: {2}", module.ModuleName, module.LinesCovered, module.LinesNotCovered));
}
Have you tried the CoverageDS.ReadXml(fileName_string) method?

What is the best solution for converting RichTextFormat info to HTML in C#?

What is the best solution for converting RichTextFormat info to HTML in C#?
I know there are libraries out there that do this, and I was curious to see if you guys had any advice as to which ones are the better ones.
Thanks,
Jeff
I recently used a RTF to HTML conRTverter that worked great, called DocFrac.
It can be used with a GUI to convert files, but it also is a DLL.
I converted over 400 RTF files to HTML in a few minutes so performance is good too. I used the GUI so I don't have the details on the DLL. According to the site the DLL works with .NET however.
DocFrac at SourceForge
Update: fixed link, because www.docfrac.net doesn't exist anymore.
Try to use this library RTF to HTML .Net. It supports RTF to HTML and text to HTML converting ways. Full version not free but there is a free trial.
This code maybe useful:
SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();
//specify some options
r.OutputFormat = SautinSoft.RtfToHtml.eOutputFormat.XHTML_10;
r.Encoding = SautinSoft.RtfToHtml.eEncoding.UTF_8;
string rtfFile = #"d:\test.rtf";
string htmlFile = #"d:\test.html";
string rtfString = null;
ReadFromFile(rtfFile,ref rtfString);
int i = r.ConvertStringToFile(rtfString,htmlFile);
if (i == 0)
{
System.Console.WriteLine("Converted successfully!");
System.Diagnostics.Process.Start(htmlFile);
}
else
System.Console.WriteLine("Converting Error!");
}
public static int ReadFromFile(string fileName,ref string fileStr)
{
try
{
FileInfo fi = new FileInfo(fileName);
StreamReader strmRead = fi.OpenText();
fileStr = strmRead.ReadToEnd();
strmRead.Close();
return 0;
}
catch
{
//error open file
System.Console.WriteLine("Error in open file");
return 1;
}
}
ScroogeXHTML, a small library for RTF to HTML / XHTML conversion, might be useful. However it only supports a subset of the RTF standard. For reports with tables and other advanced layout, there are other libraries like the Logictran R2Net converter.

Categories