This error is showing up in my code, there is a second one that is as follows:
XmlException: The existing data at the root level is invalid. Line 1, position 1
I checked this second one saying there is a error with the file when there isn't any since I have 5 files inside my XMLFiles directory.
public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
}
Console.ReadKey();
foreach (string filename in Directory.EnumerateFiles(#"C:\XMLFiles", "*.xml"))
{
ProcessFile(filename, stream, serializer);
}
void ProcessFile(string Filename, MemoryStream stream, XmlSerializer serializer)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
XmlDocument xml = new XmlDocument();
xml.Load(Filename);
ImportSession session = (ImportSession)serializer.Deserialize(stream);
foreach (Batch batch in session.Batches)
{
foreach (Document doc in batch.Documents)
{
foreach (Page page in doc.Pages)
{
if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{
if (!string.IsNullOrEmpty(page.HasError.ToString()))
{
string Import = page.ImportFileName;
Console.WriteLine("Página com erro:" + Import);
temErro = true;
}
}
}
}
}
if (temErro)
Console.WriteLine("Ficheiro com erro: " + Filename);
else
Console.WriteLine("Ficheiro processado: " + Filename);
Console.WriteLine(Filename);
}
}
public class ImportSession
{
public Batch[] Batches { get; set; }
}
public class Batch
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Description { get; set; }
[XmlAttribute]
public string BatchClassName { get; set; }
[XmlAttribute]
public bool Processed { get; set; }
public Document[] Documents { get; set; }
}
public class Document
{
[XmlAttribute]
public string FormTypeName { get; set; }
public IndexField[] IndexFields { get; set; }
public Page[] Pages { get; set; }
}
public class IndexField
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }
}
public class Page
{
[XmlAttribute]
public string ImportFileName { get; set; }
[XmlAttribute]
public string ErrorCode { get; set; }
[XmlAttribute]
public string ErrorMessage { get; set; }
[XmlIgnore]
public bool HasError => !string.IsNullOrWhiteSpace(ErrorMessage);
}
This app right now is only trying to read all the files and point out some parts that need to show up in the console and it was doing it but I was adviced on here to change into this object oriented and memory stream.
This:
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
is basically meaningless. Whatever the contents of stream are meant to be: it isn't this. Ask yourself:
What is stream meant to contain?
At the moment it contains... itself, sort of, but not really?
If you intend the stream to be the file contents: just use File.OpenRead
I think this is based on a misunderstanding from answers to previous questions on the topic.
This should make it work. BUT keep in mind, that it is in no way production-ready.
public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
foreach (string filename in Directory.EnumerateFiles(#"C:\XMLFiles", "*.xml"))
{
ProcessFile(filename, serializer);
}
Console.ReadKey();
}
private static void ProcessFile(string Filename, XmlSerializer serializer)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
using (var file = File.OpenRead(Filename)) {
var session = (ImportSession)serializer.Deserialize(file);
// from here on the rest of your code ...
To minimize the code that keeps the file opened:
ImportSession session;
using (var file = File.OpenRead(Filename))
{
session = (ImportSession)serializer.Deserialize(file);
}
// file will be closed by disposal of FileStream using this notation
// rest of code
Addendum
if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{ // Will ALWAYS be entered!
if (!string.IsNullOrEmpty(page.HasError.ToString()))
{ // Will ALWAYS be entered!
string Import = page.ImportFileName;
Console.WriteLine("Página com erro:" + Import);
temErro = true;
}
}
Let's look at it:
!string.IsNullOrEmpty(page.HasError.ToString()) is always true. Why?
page.HasError is of type bool. So, page.HasError.ToString() "Converts the value of this instance to its equivalent string representation (either "True" or "False")."
So, it will never be null or empty. So, string.IsNullOrEmpty will always be false, and !string.IsNullOrEmpty therefore always be true.
If you want to check the boolean value, you simply do if( page.HasError ) => "Page has an error"
My class structure is as follows:
class AppDetails
{
public String companyName { get; set; }
public String applicationName { get; set; }
public String version { get; set; }
public List<File_> fileObjectList { get; set; }
public AppDetails(String cName, String aName, String v)
{
companyName = cName;
applicationName = aName;
version = v;
}
}
class File_
{
public String filePath { get; set; }
public FileRecord fileRecord { get; set; }
public File_(String parent_, String filepath_, Boolean Ignored)
{
filePath = filepath_;
fileRecord = new FileRecord(parent_ + filePath, Ignored);
}
}
class FileRecord
{
public Boolean ignored { get; set; }
public String MD5Checksum { get; set; }
public int version { get; set; }
public FileRecord(String filePath, Boolean ignored_)
{
ignored = ignored_;
if (ignored)
{
MD5Checksum = null;
}
else
{
MD5Checksum = CalculateMD5(filePath);
version = 0;
}
}
static string CalculateMD5(string filePath)
{
var md5 = MD5.Create();
var stream = File.OpenRead(filePath);
var hash = md5.ComputeHash((System.IO.Stream)stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
I generated Json file using these classes. But when I try to initialize an object with the said JSON file, it throws System.ArgumentNullException: 'Path cannot be null. Parameter name: path' exception.
This is the function that is supposed to return the object.
AppDetails ReadJsonFile()
{
using (StreamReader r = File.OpenText(parent + "\\AllFilesList.json"))
{
string json = r.ReadToEnd();
var result = JsonConvert.DeserializeObject<AppDetails>(json);
return result;
}
}
I tried generating the classes from JSON using online class generators and it matches my class structure. Exception is thrown on this line:
var result = JsonConvert.DeserializeObject<AppDetails>(json);
Json string is getting loaded with the content from the file just fine(as can be seen from the watch). I couldn't find anything about Path issues related to JsonConvert.DeserializeObject. Most previous questions seems to be related to value errors.
EDIT: Serialization Code
void JsonWriter(AppDetails appDetails, String filename)
{
string path = parent + "\\" + filename + ".json";
File.Delete(path);
string json = JsonConvert.SerializeObject(appDetails);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(json.ToString());
tw.Close();
}
}
Sample Json File:
{"companyName":"Home","applicationName":"Test","version":"V5.0.1","fileObjectList":[{"filePath":"\\bug-tracker.exe","fileRecord":{"ignored":false,"MD5Checksum":"a5254a813a040b429f2288df737a8b9f","version":0}},{"filePath":"\\bug-tracker.exe.config","fileRecord":{"ignored":false,"MD5Checksum":"e5c3e9137dc8fadb57dfc27b0ba6855c","version":0}},{"filePath":"\\bug-tracker.pdb","fileRecord":{"ignored":false,"MD5Checksum":"9a9dfda29dcaacae82cba7bd7aa97ffa","version":0}},{"filePath":"\\Caliburn.Micro.dll","fileRecord":{"ignored":false,"MD5Checksum":"aa5f96c02b08d9b33322f3024058dd91","version":0}},{"filePath":"\\Caliburn.Micro.Platform.Core.dll","fileRecord":{"ignored":false,"MD5Checksum":"ab7867bd44b59879a59b5cb968e15668","version":0}},{"filePath":"\\Caliburn.Micro.Platform.Core.xml","fileRecord":{"ignored":false,"MD5Checksum":"cdfcbbf70a9a62b92e82a953ab9e7e30","version":0}},{"filePath":"\\Caliburn.Micro.Platform.dll","fileRecord":{"ignored":false,"MD5Checksum":"a52bdecbc1b7625cb13c9385fad4231b","version":0}},{"filePath":"\\Caliburn.Micro.Platform.xml","fileRecord":{"ignored":false,"MD5Checksum":"09f258a3aeca7285355d82a66dda2176","version":0}},{"filePath":"\\Caliburn.Micro.xml","fileRecord":{"ignored":false,"MD5Checksum":"c87ec582a4bfcf2e79e517c689441def","version":0}},{"filePath":"\\MaterialDesignColors.dll","fileRecord":{"ignored":false,"MD5Checksum":"ad729352a9088b889cc0c4dc7542dcb6","version":0}},{"filePath":"\\MaterialDesignColors.pdb","fileRecord":{"ignored":false,"MD5Checksum":"7ba70b23e22db9ac155e190860d9a5ec","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.dll","fileRecord":{"ignored":false,"MD5Checksum":"e4c790d3af41620dc5ad513ae7fcadac","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.pdb","fileRecord":{"ignored":false,"MD5Checksum":"f8113c8ea54896b8150db8e7ebd506ef","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.xml","fileRecord":{"ignored":false,"MD5Checksum":"49717f8130b7529ee51fb6bc13f79aa4","version":0}},{"filePath":"\\ShowMeTheXAML.dll","fileRecord":{"ignored":false,"MD5Checksum":"040b9e80820553a55f13ac19c2036367","version":0}},{"filePath":"\\System.Windows.Interactivity.dll","fileRecord":{"ignored":false,"MD5Checksum":"580244bc805220253a87196913eb3e5e","version":0}}]}
Edit 2: Json String from watch
"{\"companyName\":\"Home\",\"applicationName\":\"Test\",\"version\":\"V5.0.1\",\"fileObjectList\":[{\"filePath\":\"\\\\bug-tracker.exe\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"a5254a813a040b429f2288df737a8b9f\",\"version\":0}},{\"filePath\":\"\\\\bug-tracker.exe.config\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"e5c3e9137dc8fadb57dfc27b0ba6855c\",\"version\":0}},{\"filePath\":\"\\\\bug-tracker.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"9a9dfda29dcaacae82cba7bd7aa97ffa\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"aa5f96c02b08d9b33322f3024058dd91\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.Core.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"ab7867bd44b59879a59b5cb968e15668\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.Core.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"cdfcbbf70a9a62b92e82a953ab9e7e30\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"a52bdecbc1b7625cb13c9385fad4231b\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"09f258a3aeca7285355d82a66dda2176\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"c87ec582a4bfcf2e79e517c689441def\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignColors.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"ad729352a9088b889cc0c4dc7542dcb6\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignColors.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"7ba70b23e22db9ac155e190860d9a5ec\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"e4c790d3af41620dc5ad513ae7fcadac\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"f8113c8ea54896b8150db8e7ebd506ef\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"49717f8130b7529ee51fb6bc13f79aa4\",\"version\":0}},{\"filePath\":\"\\\\ShowMeTheXAML.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"040b9e80820553a55f13ac19c2036367\",\"version\":0}},{\"filePath\":\"\\\\System.Windows.Interactivity.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"580244bc805220253a87196913eb3e5e\",\"version\":0}}]}\r\n"
The actual issue is that you have the parameters in your constructor:
public FileRecord(String filePath, Boolean ignored_)
And JsonConvert puts there default values (null, false) which triggers the code:
else
{
MD5Checksum = CalculateMD5(filePath);
version = 0;
}
Which in its turn tries to read from a file using null path parameter:
static string CalculateMD5(string filePath)
{
var md5 = MD5.Create();
var stream = File.OpenRead(filePath); // <- HERE!!!!
var hash = md5.ComputeHash((System.IO.Stream)stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
I see there two solutions
Create parameterless constructors where init everything as you need or call the constructor with parameters using :this() with defaults:
public FileRecord() : this(null, true)
{
}
Rename properties to match parameter names, like:
public bool Ignored { get; set; }
public FileRecord(string filePath, bool ignored)
{
this.Ingnoerd = ignored;
....
}
I have 22 .csv files that I want to read and write into 1 .csv file
This is my internal class
internal class Record
{
[Name("RptDt")]
public string Date { get; set; }
[Name("Entity")]
public string Entity { get; set; }
[Name("ProdFamily")]
public string ProdFamily { get; set; }
[Name("ProdGroup")]
public string ProdGroup { get; set; }
[Name("ProdType1")]
public string ProdType1 { get; set; }
[Name("ProdTypo")]
public string ProdTypo { get; set; }
[Name("ProdType")]
public string Buy { get; set; }
[Name("Principal")]
public string Principal { get; set; }
}
This is the write and read code
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.csv", SearchOption.AllDirectories);
string numberFile = files.Length.ToString();
using (var writer = new StreamWriter(SaveTxt.Text + "\\Result_" + MonthCB.Text + "_" + YearCB.Text + ".csv"))
using (var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
for (int i = 0; i < Int16.Parse(numberFile); i++)
{
using (var reader = new StreamReader(files[i]))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Record>();
csvOut.WriteRecords(records);
}
}
}
However, the code only write data from the first 2 .csv file. How should I solve this problem?
There are lot of issues in your code, I have tried to fix many of these. Please let me know if still not working.
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.csv", SearchOption.AllDirectories);
using (StreamWriter writer = new StreamWriter(SaveTxt.Text + "\\Result_" + MonthCB.Text + "_" + YearCB.Text + ".csv"))
{
foreach (string file in files)
{
using (var reader = new StreamReader(#"C:\test.csv"))
{
while (!reader.EndOfStream)
{
writer.WriteLine(reader.ReadLine());
}
}
}
}
Usage of CsvReader can be avoided. You are doing length.ToString() and again converting to int16. This can also be avoided, because length is already int.
I have found the answer. I create a new .csv file for each input. Before this I edit from the actual file, so the size become bigger and the line also been counted even the data not exist. Now, it works just fine.
My project takes an uploaded file from the user, as well as some data points from JCrop, and crops the image to the selected portion. Then, the cropped image is given a new name, and saved to the server. However, the image is saved to the server twice, once with the new name, and once again with a completely different name.
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
[ValidImageFile]
public ActionResult _Image(ImageViewModel VM)
{
if (ModelState.IsValid)
{
//Convert from HttpPostedBase to WebImage, then crop the image
byte[] data;
using (Stream inputStream = VM.uploadFile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
var Image = new WebImage(data);
int T = VM.y1;
int L = VM.x1;
int B = Image.Height - VM.y2;
int R = Image.Width - VM.x2;
Image.Crop(T, L, B, R);
//if the user already has an image for their character, delete it.
string oldImage = HttpContext.Server.MapPath(db.Characters.Find(VM.Id).imagePath);
if (System.IO.File.Exists(oldImage))
{
System.IO.File.Delete(oldImage);
}
//generate random file name path, save file to server.
var fileName = Guid.NewGuid().ToString();
var filePath = Path.Combine("/Content/Images/charPhoto/", fileName);
var uploadUrl = HttpContext.Server.MapPath(filePath);
Image.Save(uploadUrl);
//save file path to db.
filePath = filePath + "." + Image.ImageFormat;
db.Characters.Find(VM.Id).imagePath = filePath;
db.SaveChanges();
//returns the image path to jQuery.
return Content(filePath);
}
return View();
}
VIEWMODEL
public class ImageViewModel
{
public Guid? Id { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase uploadFile { get; set; }
[Required]
public int x1 { get; set; }
[Required]
public int y1 { get; set; }
[Required]
public int x2 { get; set; }
[Required]
public int y2 { get; set; }
}
proof of duplication :
Can anybody explain to me why this happens? Is this some intentional portion of WebImage for data backup purposes? If not, what have I done wrong, and what should I do instead?
OMG
string oldImage = db.Characters.Find(VM.Id).imagePath;
if (System.IO.File.Exists(HttpContext.Server.MapPath(oldImage)))
{
System.IO.File.Delete(HttpContext.Server.MapPath(oldImage));
}
var filePath = Path.Combine("/Content/Images/charPhoto/", Guid.NewGuid().ToString() + "." + Image.ImageFormat);
Image.Save(HttpContext.Server.MapPath(filePath));
//save file path to db.
db.Characters.Find(VM.Id).imagePath = filePath;
db.SaveChanges();
//returns the image path to jQuery.
return Content(filePath);
how do I modify this code to read binary file using BinaryReader?
Example snort's log file?(text and number are include)
public string ReadFullFile()
{
using (StreamReader streamReader = new StreamReader(this.filename))
{
return streamReader.ReadToEnd();
}
}
I don't know about snort's log, but binary reader goes something like this:
class Record
{
public int Id { get; set; }
public string Name { get; set; }
}
function ReadFullFile(Action<Record> processRecord)
{
using(var file = new FileStream("whatever.bin"))
{
using(var reader = new BinaryReader(file))
{
processRecord(new Record
{
Id = reader.ReadInt32(),
Name = reader.ReadString(),
});
}
}
}
public byte[] ReadFullFile()
{
return File.ReadAllBytes(this.FileName);
}