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

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
}
}

Related

How can I add 2 cells in a CSV file in WPF?

I use the OpenFileDialog in my WPF program to give the user the option to select a .csv file and read it into the program. Now I have the path and everything from the file that the user wants and now I want to add 2 more cells to the Excel file after a button click. How should I change it so that as soon as the button is pressed, 2 columns and cells are added to the previously imported Excel file. Here is my OpenFileDialog how I get the file OpenFileDialog::
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "CVS Datei Auswählen zum Konvertieren";
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
{
tbxFiles.Items.Add(System.IO.Path.GetFileName(filename));
string temp;
var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
temp = streamReader.ReadToEnd();
test = temp;
}
}
}
SaveFileDialog:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
List<String> liste = new List<String>();
// test = test + "Hallo;";
//File.WriteAllText(dialog.FileName, test);
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(test);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{""},{""}";
}
counter++;
}
file.Close();
}
In my "test" string I have now read in what is in the cvs file via streamreader. This is what the cvs Header looks like:
Picture 1
and so how i want it look like after my C# change:
Picture2
tbxFiles = my TextBox where the path of the selected file is shown.
So how can I add additional Excel columns with associated cells to the imported Excel file in Code Behind 2?
There you go:
....
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{value1},{value2}";
}
counter++;
}
...

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);
}
}
}
}
}

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

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.

Selection of a folder path with C#

I have a WPF application in which i have this method:
public static string getFile(List<string> extensions)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string ext = "files (", filter = "";
foreach (string s in extensions)
{
ext += s + ",";
filter += "*." + s + ";";
}
ext += ")";
dlg.Filter =ext+"|"+ filter;
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
return dlg.FileName;
}
else return null;
}
I need to add another simple method which returns a folder path in which i will save new file.
How can i do this?
What is the best way to do it?
SaveFileDialog is what you need. From MSDN link:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
I'd suggest having a look at the free Ookii Dialogs for WPF. I've used it on commercial projects in the past and it's always worked really well. Native support for WPF obviously but also has a lot of options for customization and provides more consistency across different versions of Windows.

SaveFileDialog, file does not exist

I have to process an XML file (I am choosing a file with OpenFileDialog [code not present here] and when I click the second button the XML is processed to show a tree structure of that XML that has to be saved in the other file). But when I use SaveFileDialog , I want to enter a file name of the file which does not exist yet. How should I do that if I enter the filename that does not exits , an empty file will be created ?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog fDialog = new SaveFileDialog();
fDialog.Title = "Save XML File";
fDialog.FileName = "drzewo.xml";
fDialog.CheckFileExists = false;
fDialog.InitialDirectory = #"C:\Users\Piotrek\Desktop";
if (fDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fDialog.FileName.ToString());
}
string XMLdrzewo = fDialog.FileName.ToString();
XDocument xdoc = XDocument.Load(XMLdrzewo);
//// some code processing xml file
/// not ready yet, have to write to that file the tree
//structure of selected XML file
textBox2.Text = File.ReadAllText(XMLdrzewo);
When file does not exist I get FileNotFoundException was unhandled.
the code that creates your filename should be inside the if statement.
if (fDialog.ShowDialog == DialogResult.OK)
{
}
Then, you need to create a file first, eg var stream = File.Create(filename). Then you can fill that file with the "to be created stuff" and store the xml part in your newly created file.
Something like:
if (fDialog.ShowDialog() == DialogResult.OK)
{
using (var newXmlFile = File.Create(fDialog.FileName);
{
var xd = new XmlDocument();
var root = xd.AppendChild(xd.CreateElement("Root"));
var child = root.AppendChild(xd.CreateElement("Child"));
var childAtt = child.Attributes.Append(xd.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "Node Innertext";
xd.Save(newXmlFile);
}
}

Categories

Resources