I have been trying to make sense of this http://msdn.microsoft.com/en-us/library/sfezx97z.aspx which uses the SaveFileDialog, but it is hard for me to understand. I have the following code:
FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment Sample Layout Proposed - Sample Data.xlsx");
ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile);
var json = new JavaScriptSerializer().Serialize(data);
How can I output the contents of json to a .json or .txt file?
I would like to let the user either see a link/ button to click to download/ save the file to a location on their computer, or, simply display the save file dialog box so that they can save the file to a location on their computer.
EDIT (to let OP comment on what parts are not clear):
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
File.WriteAllText(saveFileDialog1.FileName,json);
}
You are looking for this, then:
File.WriteAllText(#"c:\some\path\json.txt",json);
And note that it will save the file using UTF8-encoding without a Byte Order Mark. If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding);
See here.
Update - adding sample with SaveFileDialog:
if(!string.IsNullOrEmpty(saveFileDialog.FileName))
{
//saveFileDialog.FileName should contain the full path
//according to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename.aspx
File.WriteAllText(saveFileDialog.FileName,json);
}
Related
I am working with a client application that needs to have a local repository to save updates made to a group of objects, called "Books". However, I am not able to save the objects back into the SQL server until the entire book has been updated. So the powers that be have decided to use an excel file as a repository, we are calling a work list.
The user has to be able to name the work list so that it is meaningful to them, but they cannot be able to edit the work list in excel. My idea was to create a hidden folder to store the work lists, and the app can retrieve them from that location.
Here is my question:
Is there a way to keep the windows dialog box hidden, so the user cannot choose where the file is saved to, yet pass a name to the dialog for the work
list?
I am using the standard Microsoft.Win32.SaveFileDialog currently, but I can change, if I need to, in order to accomplish this task.
Here is my SaveFileDialog code, that allows the user to change the name but also the path to where the file saves:
public void SaveToFile(string BookName)
{
var file = "";
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = string.Format("{0} \\{1} Codes", WORKLIST_SAVE_PATH, BookName); // Default file name
dlg.DefaultExt = ".xlsx"; // Default file extension
dlg.Filter = " Excel Files (.xlsx)|*.xlsx"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Save document
file = dlg.FileName;
}
else return;
File.WriteAllText(file, Export(true));
}
So I am trying to load text from a file location so I need to start off with creating a file location and then using that file location to load the text to my text boxes.
So I want to create the file location...
#"C:\Program Files (x86)\CPA\Text[number].txt"
Then in that location I would like to have my [number] text files
one.txt
two.txt
three.txt
four.txt
five.txt
six.txt
seven.txt
eight.txt
Then I need the tool to automatically load the text files to the text boxes
For my buttons to save the text I am using...
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "one|*.txt"; //Should I name it 'one.txt' instead ?
if (saveFileDialog.ShowDialog() != DialogResult.OK)
return;
File.WriteAllText(saveFileDialog.FileName, this.textBox1.Text);
I plan on using the following to get the location...
if (File.Exists(#"C:\Program Files (x86)\CPA\Text"))
{
//Load text to textboxes
}
But I am not sure how to load text to the text boxes automatically without asking the user to select the text files using open file dialogue
You can load the contents of a text file into a string variable using the File.ReadAllText method. You just pass this method the path to a file, and it will open the file, read the contents, return them as a string, and close the file.
You might consider keeping your files in a directory along with your executable. This way it's easy to find and always stays near your exe.
To get the directory that your executable lives in, you can do this:
// This requires "using System.Reflection" at the top of your .cs file
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Then you might want to have a folder underneath that directory to store your files, like a "FileData" directory:
var myFileDirectory = Path.Combine(thisExeDirectory, "FileData");
If you don't want to do this, you can just do what you are already doing:
var myFileDirectory = #"C:\Program Files (x86)\CPA\Text[number].txt";
In any case, here's an example of how you can read the contents of a file into a textbox:
// Get the full path to the file
var filePath = Path.Combine(myFileDirectory, "one.txt");
// If it exists, write the contents to a textbox
if (File.Exists(filePath))
{
textBox1.Text = File.ReadAllText(filePath);
}
Now later, if you want to overwrite the file with the contents of the text box, you can use a similar method called File.WriteAllText:
// If the directory does not exist, create it
Directory.CreateDirectory(myFileDirectory);
File.WriteAllText(filePath, textBox1.Text);
I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));
I have some data and I would like to export it to excel. I did all the code, and everything is working fine, Now I want to save that excel file to the hard drive. I could do that too. but my problem is that I couldn't know how to allow the customer to set his/her own file name.
What I have tried:
FolderBrowserDialog brwsr = new FolderBrowserDialog();
//Check to see if the user clicked the cancel button
if (brwsr.ShowDialog() == DialogResult.Cancel)
return;
else
{
string newDirectoryPath = brwsr.SelectedPath;
//Do whatever with the new path
}
the problem of that method is it is just allows the users to select the folder that the want the file to be saved to. I want to all the user to specifiy the path and the file name.
Any idea to help pleaes?
many thanks
You need to use a SaveFileDialog instead. This let's the user specify a path + filename. Check this out for more info: SaveFileDialog on MSDN
SaveFileDialog is pretty similar to FolderBrowserDialog, so you can almost replace the existing code you already have ;)
Specify File Type (EDIT)
Have a look a the Filter property.
Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*
I'm creating right now an application in C# which saves data to the file upon clicking a button. The name and locations of the file is defined by the user, and i want the program to automatically add .txt extension to the name, as well as show only 1 possible extensions in "save files as" combobox. I have this code:
SaveFileDialog Dialog1 = new SaveFileDialog();
Dialog1.DefaultExt = "txt";
Dialog1.Filter = "Pliki tekstowe | *.txt";
Dialog1.AddExtension = true;
private void button1_Click(object sender, EventArgs e)
{
if (Dialog1.ShowDialog() == DialogResult.OK)
{
System.IO.Stream fileStream = Dialog1.OpenFile();
System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
sw.WriteLine("Writing some text in the file.");
sw.WriteLine("Some other line.");
sw.Flush();
sw.Close();
}
this.Close();
}
But whenever i click the button, i have no options to choose from in the combobox, as well as the .txt extensions are not added to the file name in case the extensions is not specified by the user himself. I know i can somehow bypass that by checking if the user gave the proper extensions, and in case he didn't add ".txt" to the name but i really wanted to know, why that piecei of code doesn't function. Any help?
The problem is the space. Just change it to this:
Dialog1.Filter = "Pliki tekstowe|*.txt";
and you should be in business.
Otherwise it's trying to match files of the pattern *.txt (subtly compared to *.txt) - which you probably don't have.
take a look at the following example and see the difference:
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx
you should try firstly to add this to your filter:
"txt files (*.txt)|*.txt|All files (*.*)|*.*"
for completeness you should add the (*.txt) string in your filter for descriptive reasons (thanks for clarifying Yuck). Try it - see what happens :)
remember it is sensitive in terms of the string. so try not to put things like a space between the file extensions
I had a similar issue where the save dialog box on firefox and safari doesn't detect the file extension even though I had Content-Type header set to "application/pdf". The issue turned out to be spaces in the name of the file. I replaced the file name with '-' (hyphens) and that fixed it.