How to upload a filepath to local database and receive the file path when I click download button - c#

The problem is when I am downloading the file, I can see the path in the download file. I am not getting the actual contents of the file inside.
When I am attaching a file called sample.txt and the path for sample.txt is== C:\Users\smohan\Downloads\databse\LocalDataBaseAp\sample.txt. I can see the path gets binded with my datagrid. But when I click the cell of the grid and download the same file. The file is downloading. But when I open.. The downloaded file I can see inside is missing the actual contents, but instead the path is saved as content (i.e.) C:\Users\smohan\Downloads\database\LocalDataBaseAp\sample.txt
What's wrong with my code?
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = fileDialog.FileName;
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.CncConnectionString);
//FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] imgData;
imgData = File.ReadAllBytes(fileDialog.FileName);}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string strId = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = System.Text.Encoding.ASCII.GetBytes(s);
string strFileToSave = saveFileDialog1.FileName;
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
}

I understand what you're doing now; So, here's the pertinent code part:
objData = System.Text.Encoding.ASCII.GetBytes(s);
The problem is I think you are misunderstanding what System.Text.Encoding.ASCII.GetBytes(string) does. It does not read a file's contents; it encodes the string you pass to it. So, you are writing your file path from your Grid - not the contents of the file. This is more like what you want:
objData = File.ReadAllBytes(s);
That reads all the bytes from the file at the path you pass to it, returning a byte[], as you were using.

Related

Save with different name in C# Form Application

I have problem when I try to save my spx file with different name.
I tried lots of ways but it did not work.
How can I save my voice recorder with different name ?
if (dataGridView1.Columns[e.ColumnIndex].Name == "Export")
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string files = fbd.SelectedPath;
string source = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
string FileName = Path.GetFileName(source);
string DirectoryName = Path.GetDirectoryName(source);
try
{
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, FileName));
}
catch (Exception)
{
MessageBox.Show("You have same voice recorder in that file.");
}
}
}
}
You just have to specify a new filename in the File.Copy command.
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, "NewFileName"));
You just need to change the name on the end, if you need the user to input this name, you just have to put an new variable on the method
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, newFileName));
Here if you want to use SaveFileDialog.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
CopyFile("C://", "New Text Document.txt", files, saveDialog.FileName);

How to open only a .dat file. In C#

I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}

Save a file in text or xml depending on which radio button is checked

I have an application that allows the user to retrieve partial data in json or xml depending on which radio button is selected, the data is parsed and then displayed in some Window Application Form controls. They have the option to save the data inside the controls in either a Text file or in a XML file depending on which (the same radio buttons used to retrieve data) radio button they select.
Every time I save a file, regardless which radio button is selected, it doesn't save it in the format chosen. When I check the file on my computer, it just shows a blank document icon with the type "File."
My code looks similar to this and it's inside a button:
SaveFileDialog newData = new SaveFileDialog();
if (newData.ShowDialog() == DialogResult.OK)
{
if (jsonRB.Checked)
{
newData.DefaultExt = "txt";
string dataPath = newData.FileName;
using (StreamWriter newFile = new StreamWriter(File.Create(dataPath)))
{
//Writing string to save data
}
}
else
{
newData.DefaultExt = "xml";
XmlWriterSettings adjust = new XmlWriterSettings();
adjust.ConformanceLevel = ConformanceLevel.Document;
adjust.Indent = true;
using (XmlWriter newFile = XmlWriter.Create(newData.FileName, adjust))
{
//writing data
newFile.WriteEndElement();
}
}
}
This should do the trick:
SaveFileDialog saveDlg = new SaveFileDialog();
if(jsonRB.Checked)
{
//The default selected extension
saveDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//this is used if you select All files (*.*) but omit a extension
saveDlg.DefaultExt = "txt";
}
else
{
saveDlg.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
saveDlg.DefaultExt = "xml";
}
if(saveDlg.ShowDialog() == DialogResult.OK)
{
if (jsonRB.Checked)
{
//Save JSON
}
else
{
//Save XML
}
}

Always asking file not present in bin/debug folder

Is there any way i can take the data from the original location instead of copying the file to the bin/debug folder.
I am looking to send a file to my local printer. But my C# application is allowing to send file only when i copy the file to my bin/debug folder. Is there a way i can over come!!!
Codes:
private string image_print()
{
OpenFileDialog ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename_noext = Path.GetFileName(ofd.FileName);
string path = Path.GetFullPath(ofd.FileName);
img_path.Text = filename_noext;
string replacepath = #"bin\\Debug";
string fileName = Path.GetFileName(path);
string newpath = Path.Combine(replacepath, fileName);
if (!File.Exists(filename_noext))
{
// I don't like to copy the file to the debug folder
// is there an alternative solution?
File.Copy(path, newpath);
if (string.IsNullOrEmpty(img_path.Text))
{
return "";
}
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
string s = image_print() + Print_image();
if (!String.IsNullOrEmpty(s) &&
!String.IsNullOrEmpty(img_path.Text))
{
PrintFactory.sendTextToLPT1(s);
}
}
Try this:
private string image_print()
{
string returnValue = string.Empty;
var ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(ofd.FileName) &&
File.Exists(ofd.FileName))
{
img_path.Text = Path.GetFileName(ofd.FileName);
using (var test2 = new StreamReader(ofd.FileName))
{
returnValue = test2.ReadToEnd();
}
}
return returnValue;
}
It looks like the underlying issue is caused by these lines:
filename_noext = System.IO.Path.GetFileName(ofd.FileName); //this actually does include the extension!! It does not include the fully qualified path
...
img_path.Text = filename_noext;
...
StreamReader test2 = new StreamReader(img_path.Text);
You are getting the full file path from the OpenFileDialog then setting img_path.Text to just the file name. You are then using that filename (no path) to open the file for reading.
When you open a new StreamReader with just a filename it will look in the current directory for the file (relative to the location of the EXE, in this case bin/debug). Copying to "bin/debug" will probably not work in any other environment outside of your machine as the EXE will probably be deployed somewhere else.
You should use the full path to the selected file:
if (ofd.ShowDialog() == DialogResult.OK)
{
path = Path.GetFullPath(ofd.FileName);
img_path.Text = path;
if (string.IsNullOrEmpty(img_path.Text))
return "";//
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}

How to give custom made locations for downloading the file

I just wanted to know how can i give a custom made default location for grabbing the files.
I have uploaded a file to the local database and i have binded the file to the gird also. When i press download its showing an error called "the file is not found in location"
If i copy the particular uploaded files to the specified location i can download it easily.
So i just need to know how can i give a default location so that i can upload and downlaod the file from the same exact location.
snapshot of error: https://imageshack.com/i/ewTrmAI2j
Edited the same below code with custom made folder path. But i dont know why the file is always being asked from bin/debug/ folder. WHy its happening like this. IS there any way i can make changes to this folder.. other than bin/debug/ folder
Codes:
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = File.ReadAllBytes(fileInfo.FullName); - - - - <<<<< ERROR HERE
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
byteData = System.Text.Encoding.ASCII.GetBytes(s);
}
}
}
The FileInfo() constructor only works with a full file path. It sounds like you are trying to use the constructor with just a file name, at which point it fails when you try to read the file because its not a valid path. There are a couple possibilities for dealing with this:
Create your own MyFileInfo() class inheriting from FileInfo() and add a constructor that appends your specific path to the filename.
Simply append the path in-line in your code as:
var myPath = #"c:\folder\stuff\";
FileInfo fileInfo = new FileInfo(myPath + fileName);
Normally the path would be setup as a setting in your app.config so you could change it easily if needed.
I found the answer
codes for the binding file path to the gridview and download the file using the file path
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}

Categories

Resources