Csv file being saved in software folder csvhelper c# - c#

so I have a program that extracts a csvTable from a csvFile structured like:
string Output_Path = Output_Path_value(output_path);
string Conversion_Logic = Conversion_Logic_value(conversion_logic); //Conversion_Logic
var textwriter = Console.Out;
using (var csvWriter = new CsvWriter(textwriter, CultureInfo.InvariantCulture))
using (var writer = new StreamWriter(Output_Path + #"\" + Conversion_Logic + "_" + fileName))
using (var csv_write = new CsvWriter(writer, CultureInfo.InvariantCulture))
using (var reader = new StringReader(sb.ToString()))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.MissingFieldFound = null;
csv.Configuration.IgnoreBlankLines = true;
csv.Configuration.RegisterClassMap<CsvTable_Headers_Map>();
csv.Read();
csv.ReadHeader();
csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("__") || row[0].StartsWith("T");
var records = csv.GetRecords<CsvTable_Headers>();
csv_write.WriteRecords(records);
//csvWriter.WriteRecords(records);// this has to be before or not exist for file to save correctly
}
The purpose of this code is to save the CsvTable to a seperate file, and then save it to the that specified output path. Everything here works, however something happens is that it also saves that file to the Debug folder, when it shouldnt. How should I structure it so that it does not save it there, and only to the output path?
I am also using the open source library, csvHelper.

Related

Download a zip file from one folder location to another

using Ionic.Zip;
var savedzipFile = "C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = "D:\MyDocs";
This is what I have. I cant use webblient because its not a url. How to I save the zip file to that selected folder location? Zip file has PDFs if that matters.
This should do the trick:
var savedzipFile = #"C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = #"D:\MyDocs";
using (var sourceStream = System.IO.File.Open(savedzipFile, System.IO.FileMode.Open))
{
using (var targetStream = System.IO.File.OpenWrite(selectedfolderfromDialog + #"\" + savedzipFile.Substring(savedzipFile.LastIndexOf('\\'))))
{
sourceStream.CopyTo(targetStream);
}
}

CsvHelper "HasHeaderRecord" get only? How to append without header?

It seems in a recent (?) update the entire configuration class is read only and I cannot set HasHeaderRecord to true to allow proper appending.
How am I supposed to append without a header now? My last working implementation is below...
internal void Write(Record record)
{
using (var writer = new StreamWriter(_filepath, true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Configuration.HasHeaderRecord = true;
csv.WriteRecord(record);
csv.NextRecord();
}
}
You now have to pass a CsvConfiguration and set it there. Also, CsvConfiguration is in the CsvHelper.Configuration namespace.
CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = true
};
using (var writer = new StreamWriter(_filepath, true))
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecord(record);
csv.NextRecord();
}

Reading file from SharePoint not returning correct value

I am using the below code to read a file from sharepoint 2019 and the return values are not string. Example of return values: 0\0\0(\u0001\0\0\u001e\0\0\0\0\0\0
using (ClientContext clientContext = new ClientContext("http://sharepoint2019/sites/test/"))
{
KeywordQuery keywordQuery = new KeywordQuery(clientContext);
keywordQuery.QueryText = "SharePoint";
keywordQuery.EnablePhonetic = true;
SearchExecutor searchExecutor = new SearchExecutor(clientContext);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
clientContext.ExecuteQuery();
foreach (var resultRow in results.Value[0].ResultRows)
{
Console.WriteLine("{0}: {1} ({2})", resultRow["Title"], resultRow["Path"], resultRow["Write"]);
File file= clientContext.Web.GetFileByUrl(resultRow["Path"].ToString());
var stream = file.OpenBinaryStream();
clientContext.Load(file);
clientContext.ExecuteQuery();
FileInformation fileInformation = File.OpenBinaryDirect(clientContext, (string)file.ServerRelativeUrl);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
// Read the stream to a string, and write the string to the console.
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
}
If you are reading some files like Word (not txt file), you will need use Open Xml library to read the string in Word, filestream can't return the real string as expected:
Get Plain Text of a Word Document using Open XML (CSOpenXmlGetPlainText)
Open a word processing document from a stream (Open XML SDK)

Cannot read file in uploaded path(used by another process)

I upload a csv file to AppData folder in project solution and read the content with the code below:
using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
var reader = new StreamReader(System.IO.File.OpenRead(fs.Name));// I check path and file itself in AppData folder. its ok
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
}
But it throws IOException with message:
The process cannot access the file 'c:\path\App_Data\o_1amtdiagc18991ndq1c1k1c2v1bama.csv'
because it is being used by another process.
I couldnt get it how and why it's being used I created this file from original uploaded file with unique name..
I couldnt get it how and why its being used
Because you've not closed the stream that's writing to it:
using (var fs = new FileStream(Path.Combine(uploadPath, name), ...)
I would suggest you write the file, close the using statement so the handle can be released, then read it:
string fullName = Path.Combine(uploadPath, name);
using (var fs = ...)
{
// Code as before, but ideally taking note of the return value
// of Stream.Read, that you're currently ignoring. Consider
// using Stream.CopyTo
}
// Now the file will be closed
using (var reader = File.OpenText(fullName))
{
// Read here
}

How to Save Excel File in a specific Folder

I am exporting excel file from database using following method.But i have one problem when i am exporting excel file than it is automatically downloading to download folder and i don't want this to be happen,I want my excel file to be downloaded in my project folder
var formsection = from fs in db.FormSections
join form in Form on fs.FormId equals form.FormId
select fs;
XLWorkbook wb = new XLWorkbook();
string sheetName = "ARTICLE"; //Give name for export file.
var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(#"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Response.End();
Here is an example that converts a datatable to a .csv file and save the file to the folder of your project for me its store the file in Domestic folder as the path given by me.
private void test(DataTable dt1) {
string csv = string.Empty;
foreach (DataColumn column in dt1.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt1.Rows)
{
foreach (DataColumn column in dt1.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
}
//Add new line.
csv += "\r\n";
}
string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New 27-07 -\\Domestic\\";
string filename= #"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
string combinepath = filepath + filename;
System.IO.File.WriteAllText(combinepath,csv);
}`
You need to write the excel to your server first.
wb.SaveAs(filePath);
//encrypt the file
Encrypt(filePath);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
memoryStream.Write(bytes, 0, (int)file.Length);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
}
}
use code as below
public void ImportXLX()
{
string filePath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), #"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx");
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
Request.Files["xlsFile"].SaveAs(filePath);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
}

Categories

Resources