I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}
Related
I'm going to launch a code editor for people to create bots to disagree, it's almost all ready, but what I need help is when saving the file, I created a function that saves but when the file already exists the person have to replace, then I created a String called currentFile that will store the path of the selected file, then how do I make it just replace the text inside the file without needing to replace the file or open the save menu?
String currentFile = "C:\\Program Files (x86)\\EXAMPLE\\FILE.js";
SaveFileDialog sfd = default(SaveFileDialog);
if (fctb_code.Text.Length > 0)
{
sfd = new SaveFileDialog();
//sfd.Filter = "All Files|*.*";
//sfd.DefaultExt = "html";
sfd.ShowDialog();
string location = currentFile;
string sourcecode = fctb_code.Text;
location = sfd.FileName;
if (!object.ReferenceEquals(sfd.FileName, ""))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false))
{
writer.Write(sourcecode);
writer.Dispose();
}
}
And I want that when the file exists it just replaces the text inside the file, but when it doesn't exist it saves the file as a new one and opens SaveFileDialog.
All the code you have posted underneath sfd.ShowDialog(); can be replaced with one simple command (and an if statement)
if (sfd.FileName != "")
{
System.IO.File.WriteAllText(currentFile, fctb_code.Text);
}
No need for Streams and StreamWriters. No obtuse if logic.
To quote the documentation for File.WriteAllText, this will do overwriting for you:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
EDIT: The main issue when renaming the file is to rename xaml contents
My intuition is screaming that there is a better way to do this, but the following works, my question is to see if there a better or an already existing method that can do this
I have a small WPF app that loads xaml files and can be imported/edited and exported.
When the WPF app initialises it makes a placeholder xaml file that you can edit,
"StartingXamlFile.xaml" when exporting I used a SaveFileDialog and the user can change the name. But the contents of the XAML file is not changed according to the file name. Also when importing an existing XAMLfile then editing and exporting(changing name when exporting) the same thing occurs.
Solution:
I set up a Singleton object to hold the file name XamlFile with property content and path. Now the default is set to "StartingXamlFile" when importing this is replaced. This is done following Gang of four Singleton technique
SaveFile code that doesnt work:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*"; // Filter files by extension
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
File.WriteAllText(dlg.FileName, editedContent);
}
Save File code that does work using Replace:
if (result == true)
{
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
Just to give this question an accepted answer, I have not found a better way to this other than:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*";
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
//X:Class replacement is done here
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
XamlFile is a singleton object that contains the content of the xaml
and initial name of file when starting up or importing, so when you export it
replaces all references to the initial name
I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.InitialDirectory = #"C:\";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Code to write the stream goes here.
}
I have tried removing the if statement as well as using...
saveFileDialog1.CreatePRompt = false;
Nothing seems to work... Any ideas?
I think you want to bypass the overwrite prompt dialog.
In this case you can use
saveFileDialog1.OverwritePrompt = false;
Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.
I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
This will set Directory to the location of my executable.
Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.
Thanks for all the pointers and ideas!
The end result ended up...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
// File contents
}
Works perfectly for what I need it for.
If you want to save but you need the user to pick a filename, I would use this:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Save file
filenamepicked = true;
}
else
{
MessageBox.Show("You have to use a file name.");
}
}
My code goes like this:
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
string sourceFile = null;
string destFile = null;
string targetPath = #"..\..\Images";
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
openFileDialogForImgUser.InitialDirectory = #"D:\My Pictures";
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
fileName = openFileDialogForImgUser.FileName;
location = Path.GetDirectoryName(fileName);
sourceFile = System.IO.Path.Combine(location, fileName);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true); /* error occurs at this line */
}
else
openFileDialogForImgUser.Dispose();
}
}
}
What I'm trying to do is that I am prompting the user to select an image in an OpenFileDialog, and copy that picture to a different directory (targetPath, specifically). Everything seems to work fine except for that one line: System.IO.File.Copy(sourceFile, destFile, true);.
It says that the file is used exclusively used by another process. And that happens for any image I select.
I'm trying to look at others' solution(s) to this problem --- I have to terminate (or wait) for the process that's using my file. If so, how do I do that? Or, if that's not the answer to this, what should I do? Note that this is the only piece of code that deals with image files in my C# solution.
I think your problem involves not disposing of the Bitmap object properly. If you create a Bitmap such that it reads from a file and you don't dispose it the file remains open and locked.
Here are a couple of links:
The dispose of an OpenFileDialog in C#?
C#: Dispose() a Bitmap object after call Bitmap.save()?
As I indicate in this answer https://stackoverflow.com/a/18172367/253938 my experience with using Bitmap and on-disk files is that it's best to never let Bitmap open the file. Instead, read the file into a byte array and use ImageConverter to convert it into an Image.
You need to close the file after you're done with. Use the .Close() property to close the file.
Once you open a file to read it/use it, it opens a background process. In order for that process to end, you need to also programatically close it using the .Close()
So your code needs to have a yourFile.Close() at the bottom of your code.
In the below C# WPF code snippet, I want to load an XML document, edit the document, and save the output to a user designated location. I can use the XmlDocument.Save method to save to a pre-defined location, but how can I allow the user to save to any location like when choosing 'SaveAs'?
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\OriginalFile.xml");
doc.Save("File.xml");
see the code below; be aware that the UAC if the user select some system folder.
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Xml (*.xml)|*.xml";
if (saveFileDialog.ShowDialog().Value)
{
doc.Save(saveFileDialog.FileName);
}
Use SaveFileDialog. Sample from the article:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".xml";
dlg.Filter = "Xml documents (.xml)|*.xml"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Save document
string filename = dlg.FileName;
}