My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}
Related
I'm using Visual Studio with Selenium to build an application that goes to a web page and finds if the contents of an array are on the page. I'm running into an issue with searching the page for the array contents.. Right now it finds nothing, so it clicks to go to the next page when it shouldn't.
The array comes from a CSV file I'm loading in and it needs to search the page for a match of any of the records from the CSV file and stops.
Here is what I have so far:
OpenFileDialog ofd = new OpenFileDialog();
private double timeOut;
private void bttnImportBrowse_Click(object sender, EventArgs e)
{
ofd.Filter = "CSV|*.csv";
var fileInputs = new List<string>();
if (ofd.ShowDialog() == DialogResult.OK)
{
String chosenFile = ofd.FileName;
String safeFileName = ofd.SafeFileName;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(chosenFile))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
fileInputs.Add(line);
//Console.Write(string.Join(" ", fileInputs));
var driver = new ChromeDriver(#"C:\Users\andre_000\Documents\Visual Studio 2015\Projects\MyProject\");
driver.Navigate().GoToUrl("MySite");
var WebDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.XPath("/html/body/a[2]"))));
while (1==1) {
try
{
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
break;
}
catch (NoSuchElementException n)
{
var nextBttn = driver.FindElementByXPath("/html/body/a[2]");
nextBttn.Click();
}
}
}
}
}
catch (Exception entry)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(entry.Message);
}
}
}
Sorry i would have left a comment but am not allowed to yet. Do you have the CSV file?
I believe you are trying to find the Link text incorrectly.
Currently calling ToString() on the list
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
should probably be
var result = driver.FindElement(By.LinkText(line));
My program is supposed to be able to allow the user to be able to select a flavor of icecreame and syrup using (comboboxes) and selecting the three check boxes if they want nuts, cherries or sprinkles. WHICH IS WORKING TO THE BEST OF MY KNOWLEGE
the Other part of the Program is supposed to allow the user to save there order and open it later using StreamReader/Writer (WHICH ISNT WORKING REALLY WELL I CANT GET IT TO WRITE DOWN WHAT IS SELECTED OUT OF BOTH COMBO BOXES AND CHECK BOXES DONT WRITE EITHER. SAMETHING WITH THE OPEN IT ONLY OPENS IF I CHANGE THE INDEX NUMBER AFTER THE EQUALS)
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
//THIS IS MY SAVE BUTTON USING STREAMWRITER
//flavorBox is the Name of the comboBox that holds 3 flavors of iceCream
//syrupBox is the name of the comboBox that holds 3 syrupFlavors inside the combobox
// my check boxes for the toppings are the IF else if else statments
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(
new FileStream(sfd.FileName,
FileMode.Create,
FileAccess.Write)
);
if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else if (Cherries.Checked)
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
else if(Sprinkles.Checked)
{
this.Tag = "checked";
sw.WriteLine(Sprinkles);
}
sw.Close();
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
//THIS IS MY OPEN METHOD WHERE IT IS SUPPOSED TO DISPLAY EVERYTHING THAT USE SAVED
{
OpenFileDialog ots = new OpenFileDialog();
if (ots.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(
new FileStream(ots.FileName,
FileMode.Open,
FileAccess.ReadWrite)
);
String items;
// I tried coping my if else if statements for the save streamREader thinking that would work it doesn't DUH. I'm out of IDEAS for this COULD USE SOME HELP WITH THIS
while (!sr.EndOfStream)
{
items = sr.ReadLine();
flavorBox.Items.Add(items);
syrupBox.Items.Add(items);
if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else if (Cherries.Checked)
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
else if (Sprinkles.Checked)
{
this.Tag = "checked";
}
}
flavorBox.SelectedIndex = 1;
syrupBox.SelectedIndex = 1;
sr.Close();
}
}
First things first: if I interpret your capslock correct then I'd advise you to calm down. It's never going to be easy to find errors if you're in a rage mode.
I guess a big part of your problem may be the following lines:
if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
You check two times for syrupBox.Text and always use flavorBox.SelectedItem. I think you got syrupBox and flavorBox mixed up.
So I got the hang of doing OpenFileDialog, now I can't seem to understand SaveFileDialog. Looked at a few pages and each of them have there own ways of doing it, but none of them get down to the point of saving the text that is in the richtextbox to a file.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog exportdialogue = new SaveFileDialog();
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
exportdialogue.FilterIndex = 2;
exportdialogue.RestoreDirectory = true;
if (exportdialogue.ShowDialog() == DialogResult.OK)
{
if ((myStream = exportdialogue.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(myStream);
wText.Write("Some Text");
myStream.Close();
}
}
}
Using a richtextbox, and a normal button, also "using System.IO;" (For the Stream )
I am trying to get the button to use SaveFileDialog so it can export the content within the richtextbox to a text file.
Issue:
Unsure what I need to do from here to make it save contents from the rich text box.
Don't know why SaveFileDialog saves files with no extension when a filter is in place.
You set:
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
which only contains ONE filter, but you set:
exportdialogue.FilterIndex = 2;
which means to use the SECOND filter. (FilterIndex is 1-based).
If you set FilterIndex = 1, your file should have the extension .txt
you can use using {} block to solve the issue:
Try this:
SaveFileDialog exportdialogue = new SaveFileDialog();
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
exportdialogue.FilterIndex = 2;
exportdialogue.RestoreDirectory = true;
if (exportdialogue.ShowDialog() == DialogResult.OK)
{
using( Stream myStream = exportdialogue.OpenFile())
{
StreamWriter wText = new StreamWriter(myStream);
wText.Write("Some Text");
wText.Close();
}
}
you need to use savefile method of reach textbox and pass to it the filename from savedialogbox.
reachtextbox.SaveFile(exportdialogue.FileName);
ps: it will be something like above code.
Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}
I was reading a book on serialization. I am confused about implementing class portion or simply put i don't really understand classes(maybe).
Basically i have my application designed in this way following the steps of my book. I just dont understand the class of FileSaving and maybe where to implement it. I would like to start using serialization to save elements of a form and reloading it via xml using a "Save" and "Load" button. I have a textbox and users keys in strings into the Majorversiontextbox and this textbox.text is then stored as MajorversionLabel. Please clarify my doubts and help me out with serialization. Thanks! I will clarify any doubts about my question.
EDIT
Question 1, Why do i need to have this FileSaving class when I am only getting values from the content from the label and saving it into a xml file. Question 2, is my FileSaving class declared correctly? Question 3, why do i need Get and Set over here?
public partial class Window1 : Window
{
...
...
public class FileSaving
{
private string major;
public string Majorversion
{
get
{
return major;
}
set
{
major = value;
}
}
}
private void MajorversionupdateButton_Click(object sender, RoutedEventArgs e)
{
MajorversionresultLabel.Content = MajorversionTextBox.Text;
MajorversionupdateButton.Visibility = Visibility.Hidden;
MajorversionTextBox.Visibility = Visibility.Hidden;
MajorversionmodifyButton.Visibility = Visibility.Visible;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
Filesaving abc = new FileSaving();
abc.Majorversion = MajorversionLabel.Content;
FileStream savestream = new FileStream(path, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(FileSaving));
serializer.Serialize(savestream, abc);
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
string loadpath;
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
DialogLoad.Multiselect = false;
DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
if ((bool)DialogLoad.ShowDialog())
{
try
{
if ((checkStream = DialogLoad.OpenFile()) != null)
{
loadpath = DialogLoad.FileName;
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
{
System.Windows.MessageBox.Show("Problem occured, try again later");
}
FileSaving abc = new FileSaving();
FileStream loadstream = new FileStream(loadpath, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(FileSaving));
abc=(FileSaving)serializer.Deserialize(loadstream);
loadstream.Close();
MajorversionresultLabel.Content = abc.Majorversion;
}
}
because XmlSerializer is an object serializer, and works from the type definition
sure, that'll work
strictly speaking you don't, but the current version looks fine; XmlSerializer works for public properties or fields; you could simplify to an automatically-implemented property though: public string MajorVersion {get;set;}
But if you only want to save a single string value - is xml overfkill? File.WriteAllText / File.ReadAllText may be simpler.