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
}
Related
I use the EPPlus library to batch edit some existing XLSM files. Inside the files I replace a line of VBA code and that's it. Everything works nice, if I edit the same line in the Excel code editor by hand.
When I open some of the files with Excel 2013 (15.0.4989.1000), the following error message is shown.
We found a problem with some content in 'test.xlsm'. Do you want us to
recover as much as we can? If you trust the source of this workbook,
click Yes.
If I click yes, the repair report shows the following entry. But the message is somewhat too generic to help me further.
Removed Records: Named range from /xl/workbook.xml-Part (Arbeitsmappe)
This is my C# code, which edits the XLSM file. Can I update my code or do I have to update the XLSM-file before editing it?
static void PatchVba(string filePath, string oldCode, string newCode)
{
var wbFileInfo = new FileInfo(filePath);
using (var package = new ExcelPackage(wbFileInfo, false))
{
foreach (var m in package.Workbook.VbaProject.Modules)
{
if (m.Code.Contains(oldCode))
{
m.Code = m.Code.Replace(oldCode, newCode);
Console.WriteLine("VBA Patched in \"{0}\"", filePath);
}
}
try
{
package.SaveAs(wbFileInfo);
}
catch
{
Console.WriteLine("Could not save patched file \"{0}\".", filePath);
}
}
}
I found out what the problem is. In the edited XLSM-file, a range name is used multiple times with overlapping scope. I was too focused on my C# code to find the root cause.
So removing the named ranges solves the issue. But it would still be interesting to know, why I can edit it without problems using Excel, but not by using EPPlus.
During the execution of this script it is not detected any error, but the file isn't modified. Reading works, writing strangely not.
My script for writing:
private void firstLaunch(){
try {
StreamWriter outfile = new StreamWriter("Path/something.txt");
outfile.WriteLine("somethingElse");
outfile.Close();
}
catch (IOException ex){
MessageBox.Show(ex.Message);
}
}
The file already exists and has already been included in the project with visual studio. At the moment it is completely empty.
Could you help me?
You can use something like this:
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
Just make sure that the file has the Build Action set to Content.
If the file is empty, I would recommend creating one in the folder of your app using IsolatedStorage. That way you can check with IsoStoreSpy the contents of your file.
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
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?
I'm currently using the RSS.MET class library to open and read feeds, but I need to be able to find out if a supplied feed is actually valid. For example, if I pass it "http://www.google.com", I want it to tell me that it isn't a valid RSS feed. How would I go about doing this?
I've already tried passing it through a try .. catch block.
try
{
Rss.RssReader reader = new Rss.RssReader(cast.PodcastURL);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
But that hasn't returned the desired effect.
According to the documentation, RssReader.Read will throw an exception if it can't read the rss file. (I guess it will be an XmlException).
Well if for some reason you don't want to work with the exception method, you could load the data in a xml file and check whether it has a top node rss...
I have worked extensively with RSS and Atom feeds but haven't used any special class to handle... Linq to XML makes handling raw XML pretty easy... :)