I am having issues reading a cvs file that is in the server. I know for sure that is not a folder permission issue because I am able to upload and delete the file in the server.
the problem is here: using (StreamReader sr = File.OpenText(#"FullDomain/MyCVSFolder/Promocodes.cvs"))
This code works in local if I change the file location for a local path #"c:etc"
I will really appreaciate any help!
code:
protected void btnPreviewFile_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string line = null;
int i = 0;
try{
using (StreamReader sr = File.OpenText(#"fullDomain/MyCVSFolder/Promocodes.cvs"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
LabelAlert.Text = "Preview good";
//Display data in a GridView control
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}catch(Exception ex){
LabelAlert.Text = ex.ToString();
}
}
Here is the solution that Mihai gave me.
I replace this line
`using (StreamReader sr = File.OpenText(#"fullDomain/MyCVSFolder/Promocodes.cvs"))`
with
`using (StreamReader sr = File.OpenText(Server.MapPath("/MyCVSFolder/Promocodes.cvs")))`
Related
So I have a csv files and I want to extract its data into a datagridview and then save this to a database. I only want it to save data displayed after "Tango N$10 Voucher Benefit,10" (See the CSV file extract to understand) I am using a windows application C#. Here is what I tried so far.
try
{
var filePath = Path.GetFullPath(openAirtimeFile.FileName);
foreach (var line in File.ReadAllLines(filePath))
{
var thisLine = line;//.Trim();
if (thisLine.StartsWith("Tango", StringComparison.OrdinalIgnoreCase))
{
string[] data = File.ReadAllLines(filePath);
DataTable dt = new DataTable();
string[] col = data[0].Split(',');
foreach (string s in col)
{
dt.Columns.Add(s, typeof(string));
}
for (int i = 0; i < data.Length; i++)
{
string[] row = data[i].Split(',');
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
}
CSV file looks like this:
Please help. How do I display data after "Tango N$10 Voucher Benefit,10"?
You're doing a File.ReadAllLines two times, so your inner if statement is useless. Perhaps try something like this.
disclaimer, this only works assuming Tango will be at the start of your csv file
try
{
var filePath = Path.GetFullPath(openAirtimeFile.FileName);
bool FoundTango = false;
foreach (var line in File.ReadAllLines(filePath))
{
var thisLine = line;//.Trim();
if (thisLine.StartsWith("Tango", StringComparison.OrdinalIgnoreCase))
{
FoundTango = true;
continue; //Tango has been found, skip to next iteration
}
if (FoundTango)
{
DataTable dt = new DataTable();
string[] col = line.Split(',');
foreach (string s in col)
{
dt.Columns.Add(s, typeof(string));
}
for (int i = 0; i < data.Length; i++)
{
string[] row = line.Split(',');
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
}
I got a CSV file but in the files in using there are not comma seperaters in the file.
How can I copy this data into my database? So the CSV file and thus the database should have 1 column.
This is what I tried so far:
System.Data.DataTable csvData = new System.Data.DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path, Encoding.GetEncoding("windows-1250"))) //windows 1250 is de correcte character encoding voor europese characters
{
csvReader.SetDelimiters(new string[] { "," }); //change this maybe to something???
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData); // it return an error here saying that: `System.ArgumentException: Input array is longer than the number of columns in this table`
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);
return csvData;
So an example for the CSV would be:
test123
test45,6
test789
And in my database would be the exact same values.
EDIT: read the comment about actual delimeters so I've updated the code below, is not pretty but should give you a starting point
Why not read the file as a simple text file. One line at a time and parse the expected syntax.
Doing something like this (not tested, may not compile)
string line;
System.Data.DataTable csvData = new System.Data.DataTable();
csvData.Columns.Add("OnlyColumn", typeof(String));
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
if(line.StartsWith("-"))
continue;
DataRow newRow = csvData.NewRow();
newRow["OnlyColumn"] = line.Split('|')[1].Trim();
csvData.Rows.Add(newRow);
}
file.Close();
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);
Maybe you need to use new line as delimiter not comma. I think you can have new values in new lines?
I think you can just use StreamReader.ReadLine() for this
You should check out this link for an explanation from Microsoft.
https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx
So something like this should do it:
using (StreamReader sr = new StreamReader(csv_file_path))
{
while (sr.Peek() >= 0)
{
csvData.Rows.Add(new string[] {sr.ReadLine()});
}
}
I want 30 data in GridView. I want to read all the files in my folder and show in GridView. I am using the following code.
string folderPath = #"C:\Folder\Folder-2.0\New folder";
DataTable dt = new DataTable();
//Creating DataTable
foreach (string fileName in Directory.EnumerateFiles(folderPath, "*.txt"))
{
string contents = File.ReadAllText(fileName);
string str = string.Empty;
string s;
if (File.Exists(fileName))
{
StreamReader sr = new StreamReader(fileName);
String line;
int k = 0;
while ((line = sr.ReadLine()) != null)
{
string[] text;
if (line.Trim() != string.Empty)
{
//text = line.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
text = line.Split('^');
if (text[0].Contains("START FOOTER"))
{
break;
}
else
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i <= text.Length - 1; i++)
{
dr[i] = text[i];
}
dt.Rows.Add(dr);
k = k + 1;
}
}
}
Response.Write(k);
// Response.End;
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
s = "File does not exists";
}
}
But the above Code throws error System.OutOfMemoryException. Error is pointing at code GridView1.DataBind(); There are about 2000 files in the folder each file is of size between 1 to 2 MB. Thats why I want to use paging using DataTable. Through DataTable I want to show 30 records.
Thanks,
Please define PageSize as 30 and implement PageIndexChanging event
protected void GridView1_PageIndexChanging(object sender, GridView1PageEventArgs e)
{
// here you need create one method of your above code and call here
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
I am reading a file from which I create a dataset and I need to create a report from that dataset but this code is not working. so maybe someone could tell me what I am doing wrong I would really apreciated it or suggest another approach to this issue.
The BuildataSet function is working properly, creating the report its whats giving me problems.
public DataSet BuildDataSet(string file,string tableName,string delimeter)
{
//create our DataSet
DataSet domains = new DataSet();
//add our table
domains.Tables.Add(tableName);
String c = "VOYAGE|SAILDATE|DELIVERYDATE|AMENITY|QTY|COMPLIMENTS|MESSAGE|CABIN|1STPAXNAME|"
+"1STPAXLAST|2NDPAXNAME|2NDPAXLAST|3RDPAXNAME|3RDPAXLAST|4THPAXNAME|4THPAXLAST|SHIP|TYPE|DELIVERYTYPE|DROOM|SEATING|TABLE|GHOSTCOLUMN";
try
{
//first make sure the file exists
if (File.Exists(file))
{
//create a StreamReader and open our text file
StreamReader reader = new StreamReader(file);
//read the first line in and split it into columns
string [] columns = c.Split('|');
//now add our columns (we will check to make sure the column doesnt exist before adding it)
foreach (string col in columns)
{
//variable to determine if a column has been added
bool added = false;
string next = "";
//our counter
int i = 0;
while (!(added))
{
string columnName = col;
//now check to see if the column already exists in our DataTable
if (!(domains.Tables[tableName].Columns.Contains(columnName)))
{
//since its not in our DataSet we will add it
domains.Tables[tableName].Columns.Add(columnName, typeof(string));
added = true;
}//end if
else
{
//we didnt add the column so increment out counter
i++;
next = "_" + i.ToString();
break;
}//end else
}
}
//now we need to read the rest of the text file
string data = reader.ReadToEnd();
//now we will split the file on the carriage return/line feed
//and toss it into a string array
string [] rows = data.Split("\r".ToCharArray());
//now we will add the rows to our DataTable
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
//split the row at the delimiter
//for (int i = 0; i <= items.Count() - 1; i++)
//{
domains.Tables[tableName].Rows.Add(items);
//}
}
}
else
{
throw new FileNotFoundException("The file " + file + " could not be found");
}
}
catch (FileNotFoundException ex)
{
_message = ex.Message;
return null;
}
catch (Exception ex)
{
_message = ex.Message;
return null;
}
//now return the DataSet
return domains;
}
//#endregion
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = BuildDataSet(#"C:/Documents/GIFTCDS.TXT", "MyNewTable", "|");
GridView1.DataSource = ds;
GridView1.DataBind();
ReportDataSource rds = new ReportDataSource("MyNewTable", ds.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportViewer1.DataBind();
ReportViewer1.LocalReport.Refresh();
}
I'm getting access denied whenever I try to delete a file after finishing reading it at C:\inetpub\wwwroot\Project\temp\. I Close() and Dispose() the StreamReader properly already? I also gave full permission for NETWORK SERVICE account? Can anyone help me?
reader = new StreamReader(path + fileName);
DataTable dt = new DataTable();
String line = null;
int i = 0;
while ((line = reader.ReadLine()) != null)
{
String[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
dt.Columns.Add(new DataColumn());
foreach (object item in data)
{
DataColumn c = new DataColumn(Convert.ToString(item));
if (Convert.ToString(item).Contains("DATE"))
{
c.DataType = typeof(DateTime);
}
else { c.DataType = typeof(String); }
dt.Columns.Add(c);
}
dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
i++;
}
else
{
DataRow row = dt.NewRow();
row[0] = "";
for (int j = 0; j < data.Length; j++)
{
if (dt.Columns[j + 1].DataType == typeof(DateTime))
{
row[j + 1] = Convert.ToDateTime(data[j]);
}
else
{
row[j + 1] = data[j];
}
}
row[data.Length + 1] = DateTime.Now.ToString();
dt.Rows.Add(row);
}
}
}
DataAccess dataAccess = new DataAccess(Constant.CONNECTION_STRING_NAME);
dataAccess.WriteBulkData(dt, Constant.TABLE);
reader.Close();
reader.Dispose();
File.Delete(path);
Your File.Delete method call should take path + fileName as parameter. This is because according to this link http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx path is the full path including the filename and your path variable includes only the folder name.
I also had the problem, hence me stumbling on this post to server. I added the following line of code before and after a Copy / Delete.
Delete
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
Copy
File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);
Link: Why is access to the path denied?
You're deleting File.Delete(path); not File.Delete(path + filename);
You are opening
reader = new StreamReader(path + fileName);
But you are closing
File.Delete(path);