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.
Related
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 wish to avoid popping up the dialog for each save attempt and choose a filename once, and save without asking for filename after?
Ideally the app should show the dialog once, save the filename. Then encapsulate code saving data into a method, make the filename visible to it, and call it when needed.
Not sure how to do this.
private void SaveData() //Figure out how to remeber previous save name
{
string taxpayerLine;
string taxpayerFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
if (taxpayerFileChooser.ShowDialog() == DialogResult.OK)
{
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer txp in taxpayerBindingSource)
{
taxpayerLine = txp.Display(",");
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose(); //Destructor
MessageBox.Show("Data Saved to: "
+ System.IO.Path.GetFileNameWithoutExtension(taxpayerFile));
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 my form I have a button that launches the SaveFileDialog module. Then when I load a file, I want to save the path as a string and put that text into a text box on the form. I'm not sure how to do this, or even where to start?
Well the problem with your question is that you say when you "load a file", but you cannot load a file from the SaveFileDialog module. However, if you are opening a file via the OpenFileDialog module, then you are able to use this solution to get the directory path of the file you just loaded:
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
if(!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
Otherwise, if you are wanting to get the file path of whatever file you saved originally, you can use pretty much the same solution to get the directory path:
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(saveFileDialog1.FileName);
if (!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
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");
}