Export text to a browsed file in wpf - c#

I'm trying to export some text to a file browsed by the user and create it if this file does not exists.
What I've done till now is to use OpenFileDialog but I don't know if it's the right way to do it and also if it is I don't know how to continue

You can use the SaveFileDialog()
var dialog = new SaveFileDialog();
dialog.ShowDialog();
var path = dialog.FileName;
File.WriteAllText(path, "YourData");

Related

C# WPF Have User select file then use the functions within that file

I'm new to using C# and WPF so I apologize if my terminology is incorrect.
I want trying to make a program to automate small businesses workflows, the base application is the same for everyone, but how their order data is structured is going to be different.
So, my goal would be to build them a custom file that contains function on how to parse their order data, then have the user drag and drop that file into the application to which the application would use it.
I have a way for them to select the file and move it into the applications directory here:
private void SelectFile_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".cs";
dlg.Filter = "C# Files (*.cs)|*.cs";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filePath = dlg.FileName;
string relPath = AppDomain.CurrentDomain.BaseDirectory;
string destPath = System.IO.Path.Combine(relPath, dlg.SafeFileName);
Trace.WriteLine(destPath);
File.Move(filePath, destPath, true);
}
}
But now I run into an issue when I want to call from that file I get a error "CS0103" the file doesn't exist in the current context. So I am now unable to run the application
Is there a way around this error? so it will only run when the file exists and get rid of this error?
I have tried to check if the file exists before calling it, but the same error prevents me from running my app.
//call your order parser script
if (File.Exists("OrderParser.cs"))
{
OrderParser.OrderParser.Parser(item);
}

C#- How to use OpenFileDialog to load a ConfigurationUserLevel file?

I want to be able to load a config file (.config) of type System.Configuration.ConfigurationUserLevel using OpenFileDialog.
I need the file to be a ConfigurationUserLevel because the I need to use .AppSettings, as its functionality already exists in many other places throughout my code.
Currently I have,
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var extension = Path.GetExtension(openFileDialog1.FileName);
if(extension.Equals(".config"))
{
try
{
var configFile = (ConfigurationUserLevel)openFileDialog1.OpenFile();
var settings = configFile.AppSettings.Settings;
but I get an error saying that I cannot simply convert from a Stream to ConfigurationUserLevel.
Is there a way for me to get a ConfigurationUserLevel file from an openFileDialog? Or is there a workaround?
OpenFileDialog just helps users to get FileName, of course you can't open file directly with openFiledialog.OpenFile().
You need to read file with FileName from OpenFileDialog, and parse it then cast to ConfigurationUserLevel.
This can be help: https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx

InitialDirectory not working

VERY VERY new to C Sharp, as it's not part of my study path, but I have to edit small codes in C Sharp in order for my app to work. I'm using Ogama, a open source gaze tracker, which I need for my project. The heatmap, to be more specific. Now, I want to save the heatmap to a directed folder, and managed to find the code. The initial code was
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
So I thought I could change it, by following other tutorials online, and this was my code.
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "heatmapimages");
But it doesn't work. When I click the save file button, it brings me to where my Ogama projects are. The 'heatmapimages' folder is in my Desktop. Any advice? Thank you in advance.
EDIT: Managed to make it work, by changing Special.Personal to Special.DesktopDirectory. Is there a way to make it autosave the image? Such that I don't need to click save?
You need to set RestoreDirectory true and set InitialDirectory to SpecialFolder.Desktop. Here are all SpecialFolders for your reference.
It restores the current directory to its original value if the user changed the directory while searching for files.

SaveDialog file exist?

I use this code to save an avi file. When I create a new file, it's no problem.
But When I choose an existing file, It does not work and saveFileDialog still shows.
I have set saveDialog.OverwritePrompt and saveDialog.CheckFileExists is true, but it is not ok. If I set saveDialog.OverwritePrompt is false it runs, but it does show overwrite warning
How can I solve this?
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.OverwritePrompt = true;
DialogResult dgResult = saveDialog.ShowDialog();
if (dgResult == DialogResult.OK)
{
exportAvi(saveDialog.FileName);
}
This code works - if I choose to overwerite an existing file it shows me the Prompt:
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.OverwritePrompt = true;
DialogResult dgResult = saveDialog.ShowDialog();
if (dgResult == DialogResult.OK)
{
//exportAvi(saveDialog.FileName);
}
[Window Title]
Confirm Save As
[Content]
XYZ.txt already exists.
Do you want to replace it?
[Yes] [No]
Your issue is in the exportAvi() function. You are not allowing for the file to be overwritten. I cannot see your exportAvi() function so I cannot tell you what is wrong exactly. If you post your exportAvi() function I can help you further.
saveDialog.OverwritePrompt - will only prompt the user if they want to overwrite. It will not overwrite the file. You have to handle this in your code.
saveDialog.CheckFileExists - will only check if the file exists.
Check your export function and make sure you are setting the overwrite parameter to True.

Create, write to and open a text file from SaveFileDialog

I am displaying a SaveFileDialog and when OK is clicked I am creating new file, writing some default content to it and then attempting to Open it via the OpenFile() method of the SaveFileDialog. However, the moment I call OpenFile() the content of the file are deleted.
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML files (*.xml)|*.xml";
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// First Event Creates file and writes default content to it - works ok
NewFileCreated( this, new FileCreatedEventArgs() { Template = Template.BBMF, FilePath = saveFileDialog.FileName } );
// Second Event clears file content as soon as saveFileDialog.OpenFile() called
FileLoaded( this, new FileLoadedEventArgs() { FileStream = saveFileDialog.OpenFile() } );
}
Can someone explain why this happens and what I need to be doing to successfully Open the newly created file?
According to MSDN, SaveFileDialog.OpenFile()
Caution
For security purposes, this method creates a new file with the
selected name and opens it with read/write permissions. This can cause
unintentional loss of data if you select an existing file to save to.
To save data to an existing file while retaining existing data, use
the File class to open the file using the file name returned in the
FileName property.

Categories