Reading .csv file from file upload control gives File not found exception - c#

I am trying to upload .csv file to SQL database, as per my code below when I am trying to read .csv file by assigning the File PATH to a variable my program runs fine, but when I am retrieving the same PATH from File Upload control I am getting File Not Found Exception.
Can anyone please guide me how to get ride off this error. Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.VisualBasic.FileIO;
using System.IO;
public partial class Exercise1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fupPath.HasFile)
{
string csv_file_path = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
//string csv_file_path = Path.Combine(Server.MapPath("~/File"), fupPath.FileName);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
}
}
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
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);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
//protected void btnSubmit_Click(object sender, EventArgs e)
//{
// if(fupPath.HasFile)
// {
// //string csv_file_path = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
// String csv_file_path = Path.Combine(Server.MapPath("~/File"), fupPath.FileName);
// fupPath.SaveAs(csv_file_path);
// //string path = Server.MapPath("~/")
// //String csv_file_path = Server.MapPath(fupPath.FileName).ToString();
// //csv_file_path = csv_file_path.Replace(#"\\","\"");
// DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
// Response.Write("Rows count:" + csvData.Rows.Count);
// }
//}
}

you need to save the file first
if (fupPath.HasFile)
{
string filename = Path.GetFileName(fupPath.FileName);
String csv_file_path = Path.Combine(Server.MapPath("~/File"), filename);
fupPath.SaveAs(csv_file_path);
and then read it
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
In your commented Code Path.Combine(Server.MapPath("~/File"), fupPath.FileName); will not work because fupPath.FileName contains the Full path.

If you want to read a file which is present in your local system.You need to save the file first in required location and then you have to read that file by using that location .
Solution:fupPath.SaveAs(csv_file_path);
i.e;
if (fupPath.HasFile)
{
string csv_file_path = Path.Combine(Server.MapPath("~/File"),fupPath.FileName);
fupPath.SaveAs(csv_file_path);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
}
*Reason:*In order to read file,first we have to know the location of the file.file upload control doesn't give file location(Because of security problems).By using file upload control we can save file in our required location.Then by using that location we can read file.If you don't want to save file.After reading file you can delete that file.

Related

How to transfer files form folders and sub-folders to specific folders created by file name pattern in C# (File2specific Folders)

As you can see in code, folders are created during move file button. my question is that how to moves files in that particular folders, I have tens of millions of files and want to moves in that particulars. I am new in c#.
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace File2Folders
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> fileName = null;
List<string> fileNames = null;
private void btn_browse_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
fileName = Directory.GetFiles(fbd.SelectedPath).ToList();
fileNames = fileName.Select(item => Path.GetFileNameWithoutExtension(item).Substring(1, 4)).OrderBy(n=>n).ToList();
listBox1.DataSource = fileName.Select(f => Path.GetFileName(f)).ToList();
listBox2.DataSource = fileNames;
}
}
}
private void btn_move_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
fileNames.ForEach(item => Directory.CreateDirectory(Path.Combine(fbd.SelectedPath, item)));
}
Try to use this fuction that I use sometimes.
bool FileCopyPasteRename(string source, string destination, string renameTo)
{
bool res = false;
string renameDestination = Path.Combine(destination, renameTo.ToLower());
try
{
if (File.Exists(source))
{
File.Copy(source, renameDestination, true);
}
}
catch (Exception ex)
{
//cath error ex.Message
}
return res;
}
Once its a bool function, you can check if returns true and the delete source file.
To move a file you can use method Move in File. It takes as parameter the path of the file you want to move and the destination including and the file name
here is an example
string filePath = #"C:\Users\HP\source\repos\ConsoleApp1\ConsoleApp1\fileToMove.txt";
string destination = #"C:\Users\HP\source\repos\ConsoleApp1\ConsoleApp1\Dummy\fileToMove.txt";
try
{
File.Move(filePath, destination);
}
catch (Exception e)
{
Console.WriteLine("We coudnt move the file becouse of: " + e.Message);
}
For more https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?view=net-6.0

converting excel macro to C#

i am creating VSTO in excel , for this i am converting the existing macro to c# where have to find minimun of the column , i have converted this far as shown below :
using Microsoft.Office.Tools.Ribbon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Interop.Excel;
namespace CpCpk
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
var excelApp = Globals.ThisAddIn.Application.ActiveSheet;
//excelApp.Workbooks.Add();
excelApp.Range["P2"].Select();
excelApp.ActiveCell.FormulaR1C1 = "=MIN(C[-14])";
excelApp.Range["Q2"].Select();
excelApp.Visible = true;
}
}
}
now i am not getting any error in syntax , but during execution i am getting below rror:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'ActiveCell''
in the line :
excelApp.ActiveCell.FormulaR1C1 = "=MIN(C[-14])";
somebody please help me how to correct this..
You need to set FormulaR1C1 directly from specific cell
excelApp.Range["P2"].FormulaR1C1 = "=MIN(C[-14])";
You could just convert the spreadsheet to a datatable via closed xml (via nuget) like so:
public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.
DataTable dt = new DataTable();
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(path))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
}
i++;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}
Then get the minimum via linq:
var min = dt.AsEnumerable()
.Min(r => r.Field<Decimal>(col));
Reminder, you'll need using System.Linq; and using ClosedXML.Excel;

saving an encrypted piece of text and then opening an decrypting it using a GUI application

i have built an application where I can input a word or message into a textbox and click on my cipher button this will then generate a random key and encrypt that message I can then decipher that message by clicking my decipher button.MY problem is with my new features of a save and open button with this I want to save a message in its RAW enciphered format then be able to open it and decipher it as well as any other messages that have already been enciphered and previously saved. my problem is that this is not working I think it might be a problem with my save button because I also need to save the key as well as the message to decipher the message correctly this is just one of the things I have tried and I am quite stuck with this problem any help would be appreciated.Also the cipher I am using is the caesar cipher
the image is the GUI of the first stage of my working application with the message uptown funk being encryption. And obviously below is the code.
Edit-I have tried creating a tuple class to solve my problem but I have only used a class once never mind a tuple class and to put it bluntly after staring at it for a few hours I do not know how to get this to work some assistance would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
namespace login_form
{
public partial class Main : Form
{
public string cipherText;
public string originalText;
public string DecipherText;
public int key;
public Main()
{
InitializeComponent();
}
public static char cipher(char ch, int key)
{
if (!char.IsLetter(ch))
{
return ch;
}
char d = char.IsUpper(ch) ? 'A' : 'a';
return (char)((((ch + key) - d) % 26) + d);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += cipher(ch, key);
return output;
}
public static string Decipher(string input, int key)
{
return Encipher(input, 26 - key);
}
private void Main_Load(object sender, EventArgs e)
{
}
private void btnCipher_Click(object sender, EventArgs e)
{
Random rndNumber = new Random();
tbKey.Text = rndNumber.Next(0, 26).ToString();
originalText = tbWord.Text;
try {
key = Convert.ToInt32(tbKey.Text);
}
catch {
MessageBox.Show("Invalid Input! Please Try Again");
}
cipherText = Encipher(originalText, key);
tbOutput.Text = Convert.ToString(cipherText);
}
private void btnDecipher_Click(object sender, EventArgs e)
{
DecipherText = tbOutput.Text;
string DecipherOutput = Decipher(cipherText, key);
tbDecipheredOutput.Text = Convert.ToString(DecipherOutput);
}
private void btnOpen_Click(object sender, EventArgs e)
{
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
tbOutput.Text = fileContent;
MessageBox.Show("Path of File: " + filePath);//shows the path of the file
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";//the format the file will be saved in
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//saves the folder to my documents
string Content = tbOutput.Text;//saves the contens of textbox output
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
File.WriteAllText((saveFileDialog1.FileName), Content);
}
catch (IOException)
{
MessageBox.Show("File Was not Saved");
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace login_form
{
class tuple
{
int key;
string cipherText;
static public void Main()
{
// Creating tuple with two elements
// Using Create method
var My_Tuple = Tuple.Create("lol", 23);
Console.WriteLine("Element 1: " + My_Tuple.Item1);
Console.WriteLine("Element 2: " + My_Tuple.Item2);
}
}
}

How can to insert update and delete records in a csv file obtained with OpenFileDialogue as datasource in datagridview

I am trying to come up with a solution which reads CSV files and edit them from open file dialogue
I'm able to read the file and display it to the data grid view but can only edit or update from the data grid, not with textboxes and button.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "CSV Files (*.csv)|*.csv";
if (dialog.ShowDialog() == DialogResult.OK)
{
DataTable table = CSVReader.ReadCSVFile(dialog.FileName, true);
dataGridView1.DataSource = table;
}
assist with the syntax for editing CSV files
I had to read this question a few times before I fully understood what you are asking for. As I understand it, you want to do Insert, Update, and Delete operations in a DataGridView, and then write the results to a CSV file, right. You don't want to do the operations directly on the CSV file, right. With that clarified, try the script below and feed back.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtFile.Text = openFileDialog1.FileName;
BindData(txtFile.Text);
}
private void BindData(string filePath)
{
DataTable dt = new DataTable();
string[] lines = System.IO.File.ReadAllLines(filePath);
if (lines.Length > 0)
{
//first line to create header
string firstLine = lines[0];
string[] headerLabels = firstLine.Split(',');
foreach (string headerWord in headerLabels)
{
dt.Columns.Add(new DataColumn(headerWord));
}
//For Data
for (int i = 1; i < lines.Length; i++)
{
string[] dataWords = lines[i].Split(',');
DataRow dr = dt.NewRow();
int columnIndex = 0;
foreach (string headerWord in headerLabels)
{
dr[headerWord] = dataWords[columnIndex++];
}
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
csv += column.HeaderText + ',';
}
//Add new line.
csv += "\r\n";
//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null)
{
//Add the Data rows.
csv += cell.Value.ToString().TrimEnd(',').Replace(",", ";") + ',';
}
// break;
}
//Add new line.
csv += "\r\n";
}
//Exporting to CSV.
string folderPath = "C:\\Users\\Excel\\Desktop\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(folderPath + "test.csv", csv);
MessageBox.Show("");
}
catch
{
MessageBox.Show("");
}
}
}
}

How to use C# to convert any file to some other arbitrary format(.rjb) & recover to original format?

This is my first question in Stackoverflow
I am trying to convert some files(.txt,.mp3,.mp4,.pdf,.png,.exe etc.) in a folder to a format .rjb, created by me. And I also want to recover the original files from the .rjb files. But every files other than .txt files get corrupted. Please help me, to accomplish this. The below code is what I am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rjbformat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
//string data = Convert.ToString(File.ReadAllBytes(textBox1.Text));
// string datas = File.ReadAllText(textBox1.Text);
//string dat = File.ReadAllText(textBox1.Text, Encoding.ASCII);
//var dataS = Convert.ToString(datas);
using (StreamWriter sw = new StreamWriter(textBox1.Text + ".rjb"))
{
sw.Write(textBox3.Text);
}
}
catch (Exception)
{
MessageBox.Show("Specified Input file DOESNOT EXIST!", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
//throw;
}
}
else
{
MessageBox.Show("Please select Input file");
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Text File (Rajib)";
openFileDialog1.Filter = "Text Files(*.txt;*.cod;*.ubc)|*.txt;*.cod;*.ubc";
openFileDialog1.Filter = "All Files(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
textBox2.Text = openFileDialog1.FileName + ".rjb";
File.Copy(textBox1.Text, textBox2.Text,true);
FileAccess.ReadWrite.ToString(textBox1.Text);
var lines = File.ReadAllLines(textBox1.Text);
/* foreach (string line in lines)
{
textBox3.Text += line+"\r\n";
}*/
File.AppendAllLines(textBox2.Text, lines);
// FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
// int hexIn;
// String hex = "";
// for (int i = 0; i<50/*(hexIn = fs.ReadByte()) != -1*/; i++)
// {
// hex = string.Format("{0:X2}", fs.ReadByte());
// // int bina = fs.ReadByte();
// textBox3.Text += hex;
//}
}
}
}
}
If all you are doing is storing one or more files into your .rjb format and want to get them back intact, this sounds a lot like creating archive files. In that case, you may want to consider just using a standard zip file and customize the extension.
Here's an example using the ZipArchive class:
using System.IO.Compression;
namespace CustomZip
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.rjb";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You will need to add a reference to System.IO.Compression.FileSystem to your project.

Categories