Reputation: 1
I have a method that returns a .txt file. As it is, it saves it in the debug folder of my project. I however aim to create a button that saves the .txt file to wherever the user wants it to be saved.
This is the method that creates the .txt file
public static void Createtxtfile(string file)
{
string textPath = @"" + file + ".xml";
int capacity = 1000000;
int maxCapacity = 999999999;
StringBuilder textfile = new StringBuilder(capacity, maxCapacity);
InitializeProject(File.ReadAllText(textPath), textfile);
CreateATextFile(textfile.ToString(), "textfile-" + file + ".txt");
}
This works great so far. CreateATextFile is a function that reads everything from textfile and dumps it into the debug folder, like so.
public static void CreateATextFile(object data, string fileName)
{
var stream = new FileStream(fileName, FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(data);
writer.Close();
}
}
I would like to code a button that saves the textfile to a user specified location, but cannot figure out what would be the best course of action.
public void icon_dl_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == true)
File.WriteAllText(saveFileDialog.FileName, textfile.ToString());
}
I understand why the textfile is not recognized in the button click method, as it is created in the Createtxtfile method. Is there a way to allow access to the same file despite the varying methods? I'm not looking to call upon the Createtxtfile method again when pressing the download button
EDIT :
The InitializeProject method initializes the stringbuilder. This is done out of functions that are being received via the .dll file attached
[DllImport("Textfunctions.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void InitializeProject(
string file,
StringBuilder textfile,);
Upvotes: 0
Views: 165
Reputation: 395
If I understand your description correctly, your problem is in icon_dl_Click(), the variable textfile is unknown?
If so, you can make the textfile a variable known to both Createtxtfile() as well as icon_dl_Click(). Which means in Createtxtfile(), instead of saying
StringBuilder textfile = new StringBuilder(capacity, maxCapacity);
you should declare StringBuilder textfile outside of it, such as a class member variable. So in Createtxtfile() you say
this.textfile = new StringBuilder(capacity, maxCapacity);
and in icon_dl_Click() you say
File.WriteAllText(saveFileDialog.FileName, this.textfile.ToString());
Assuming these two methods are in the same class. Of course, then you don't really need "this.", just "textfile".
Does this answer your question?
Upvotes: 1