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);
}
}
Related
I have created a software, which save some Information in an Excel File. The software has two possibilities:
To select the folder and then the software will create an Excel File with random name and there will save the data , or
To select an existed Excel File which is created from the user and there will save the data.
How to create a ONE ShowDialog to ask the user do you want to choose the folder or the file?!
Code that I have used to choose a Folder:
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
textBox3.Text = fbd.SelectedPath;
}
}
Code that I have used to choose a File:
OpenFileDialog excelFilename = new OpenFileDialog();
if (excelFilename.ShowDialog() == DialogResult.OK)
{
textBox3.Text = excelFilename.FileName;
}
Maybe something like this?:
MessageBoxResult result = MessageBox.Show("Ask user what he wants to do", "", MessageBoxButton.YesNo);
string path = null;
//MessageBoxResult.Yes means File, .No means Folder
if (result == MessageBoxResult.Yes)
{
//File-Picker
OpenFileDialog filePicker = new OpenFileDialog()
{
FileName = "Excel File",
DefaultExt = ".xls",
Filter = "Excel Document | *.xls"
};
if (filePicker.ShowDialog() == true)
{
path = filePicker.FileName;
}
}
else if (result == MessageBoxResult.No)
{
//Folder-Picker
CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
{
IsFolderPicker = true,
Multiselect = false
};
path = Path.Combine(folderPicker.FileName, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
//Create file in folder
File.Create(path);
}
if (path != null)
{
// Do something with path (file user selected/program created)
}
Make sure you have the using System.Windows, using Microsoft.Win32; and using System.IO; using's at the beginning of your program.
You also have to add the WindowsAPICodePack library to your project to use the folder-picker. You can do that with the NuGet manager. Here's the link to the library: WindowsAPICodePack - 1.1.1
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
}
}
string filename = "";
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = #"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
lines = File.ReadAllLines(RecentFiles);
filename = theDialog.FileName;
for (int i = 0; i < lines.Length; i++)
{
recentfiles = new StreamWriter(RecentFiles, true);
recentfiles.WriteLine(theDialog.FileName);
recentfiles.Close();
items = File
.ReadLines(RecentFiles)
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
TextFileContentToRichtextbox(filename);
}
}
I'm not sure if doing the for loop over the lines is right.
But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.
Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.
Linq is perfect for this:
// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
// then write it into recent files text file
}
//// the below code will work only if a line has 1 fileName with extension or any text.
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.
I created a notepad, however i want to save the file using the FolderBrowserDialog. Now i can't save the file because of this error: An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: The specified path is not supported.
this is the code i enterd:
private void Create_button_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are you sure to make the file", "Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
StreamWriter File = new StreamWriter(files + "." + groupBox3);
File.Write(textBox4);
}
}
else if (dialogResult == DialogResult.No)
{
}
}
can somebody help me?
a few things here to cause problems:
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
Here you read the existing files in that directory. I thought you wanted to create a file? IN that case you provide a destination path, e.g.
var dest=Path.Combine(openfileDialog1.SelectedPath,"myfile.txt");
The following especially will not work:
StreamWriter File = new StreamWriter(files + "." + groupBox3);
You are passing a string array here. You need to pass a string as argument, not an array. See above. Also you try to name it like (which?) existing file + an extension determined by some groupBox3?
Writing the file, assuming that textBox4 contains the contents to be written, needs to be specified via the .Text property:
File.Write(textBox4.Text);
Please be specific as to which control or variable contains the desired output filename, which the contents, and what groupBox3 is supposed to provide.
Edit:
RadioButton suffix = groupBox3.Controls.OfType<RadioButton>().FirstOrDefault(n => n.Checked);
if (suffix == null)
MessageBox.Show("Please select a valid extension first");
else
{
var extension = suffix.Text;
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var dest = Path.Combine(openfiledalog1.SelectedPath, "NewFile." + extension);
using (StreamWriter File = new StreamWriter(dest, false))
{
File.Write(textBox4.Text);
}
}
}
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);
}
}
}
}
}