in C#, save multiple files in selected path in saveFileDialog - c#

I am using C# with sliverlight 5. I am using SaveFileDialog to get the userselected file name. Now I need to save multiple files at same location with different extensions. I tried the following
string directory = System.IO.Path.GetDirectoryName(dialog.SafeFileName);
Stream fileStream = dialog.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
string sequenceFASTAFileNAme = System.IO.Path.GetFileNameWithoutExtension(dialog.SafeFileName) + ".fa";
string path = System.IO.Path.Combine(directory, sequenceFASTAFileNAme);
if (!File.Exists(sequenceFASTAFileNAme))
{
StreamWriter tw = File.AppendText(System.IO.Path.Combine(directory,sequenceFASTAFileNAme));
tw.WriteLine("The next line!");
tw.Flush();
tw.Close();
}
But I am getting following error
File operation not permitted. Access to path 'helo.fa' is denied.
at
StreamWriter tw = File.AppendText(System.IO.Path.Combine(directory,sequenceFASTAFileNAme));
How can I just get the path of the selected file.

private void button1_Click_1(object sender, EventArgs e)
{
string[] FileV = new string[3];
FileV[0] = "val1";
FileV[2] = "val2";
FileV[3] = "val3";
save(FileV);
}
private void save(string[] FileValue)
{
System.IO.Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
System.IO.StreamWriter tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex1");
tw.WriteLine(FileValue[1]);
tw.Flush();
tw.Close();
tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex2");
tw.WriteLine(FileValue[2]);
tw.Flush();
tw.Close();
tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex3");
tw.WriteLine(FileValue[3]);
tw.Flush();
tw.Close();
myStream.Close();
}
}
}

Related

How do I overwrite a file if it already exists?

I'm making a text editor using fastColoredTextbox. I have a button that allows you to save your text onto your pc. The problem is that it throws an exception when the user tries to save the file as a file that already exists, instead of overwriting the file.
This is my code.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
How would I go about making it overwrite the file if it already exists?
Maybe this could help you:
sw = new StreamWriter(path, true);
sw.WriteLine(line);
https://learn.microsoft.com/es-es/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean)
I changed up my code a bit and ended up going with this, which somehow got it to work.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream s = saveFileDialog1.OpenFile();
StreamWriter sw = new StreamWriter(s);
sw.Write(fastColoredTextBox1.Text);
sw.Close();
}

Copy a file but with a "Save as" window

I just want to copy a file to another location. But with a FileDialog.
I tried the code below but this is not working as I want...
Is there any other solution ?
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
System.IO.File.Copy(Path, newDirectory);
}
EDIT :
I want something like this :
Word exemple
A Filedialog with the default name of my source file and the right type. You can see an example when you try to save a Word.
Use the FileStream class . Which is more flexible, especially if you want to track the data transfer process byte by byte.
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
byte[] buffer = new byte[1024 * 1024];
int currentBlockSize = 0;
using (source = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
using (dest = new FileStream(newDirectory, FileMode.CreateNew, FileAccess.Write))
{
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
}
}
}

How do I get a random word from a .txt file using C#?

private async void Button_Click(object sender, RoutedEventArgs e)
{
int word = 1;
string FileName;
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
openFileDialog1.FilterIndex = 2;
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ShowDialog();
FileName = openFileDialog1.FileName;
FileStream stream = File.Open(FileName, FileMode.Open);
await Task.Run(() =>
{
using (StreamReader reader = new StreamReader(FileName))
{
string content = reader.ReadToEnd();
}
});
}
As you can see, I decided to create a "content" string that would contain all the text inside of a .txt file. How do I now select a random word from this string that is not an array?
You should split on the spaces and then use random to get a random integer.
Random random = new Random();
string[] split = content.Split(" ");
string randomString = split[random.Next(0,split.length)];

C# How to load a Canvas with XML

my problem is that I can't figure out how to load a Canvas type object from an XML file. I hope you can help me.
This is what I was trying, I'll show you the code of how I'm doing the serialization too, just in case I did something wrong.
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "XML Files(*.xml) | *.xml | Text Files(*.txt) | *.txt | All Files(*.*) | *.* ";
sfd.ShowDialog();
MainWindow mainWindow = new MainWindow();
SerializeToXML(mainWindow, designSpace, 96, sfd.FileName);
mainWindow.Close();
}
public static void SerializeToXML(MainWindow window, Canvas canvas, int dpi, string filename)
{
string mystrXAML = XamlWriter.Save(canvas);
FileStream filestream = File.Create(filename);
StreamWriter streamwriter = new StreamWriter(filestream);
streamwriter.Write(mystrXAML);
streamwriter.Close();
filestream.Close();
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
var fileContent = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
ofd.FilterIndex = 2;
ofd.RestoreDirectory = true;
ofd.ShowDialog();
var fileStream = ofd.OpenFile();
string boi = ofd.FileName;
// Create an instance of the XmlSerializer specifying type.
XmlSerializer serializer =
new XmlSerializer(typeof(Canvas));
// Create a TextReader to read the file.
FileStream fs = new FileStream(boi, FileMode.Open);
TextReader reader = new StreamReader(fs);
// Use the Deserialize method to restore the object's state.
designSpace = (Canvas)serializer.Deserialize(reader);
}
The app works well until I try to load an XML file, that's when this exception pops out:
System.InvalidOperationException: 'Error to reflect type System.Windows.Controls.Canvas'.'
NotSupportedException: Can not serialize the member
System.Windows.Input.InputBinding.Command type
System.Windows.Input.ICommand because it's an interface.
I did
in Saving:
string xml = XamlWriter.Save(cssave);
using (StreamWriter fl = new StreamWriter(path, false))
{
fl.Write(xml);
}
In Loading:
string xml = File.ReadAllText(currpath);
//Convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
MemoryStream stream = new MemoryStream(byteArray);
Canvas cs = (Canvas)XamlReader.Load(stream);
csmain.Children.Add(cs);

How to save BitmapImage via SaveFileDialog from WPF?

The way I try implement it via standart Windows.Forms (to get valide DialogResult.OK)
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
// dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
if(dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK)
if (dlg.DialogResult.HasValue && splashDialog.DialogResult.Value)
{
string fName = dlg.FileName;
if (dlg.FileName != "")
{
System.IO.Stream fileStream = (System.IO.FileStream)dlg.OpenFile();
fileStream.Close();
}
}
This is using Windows forms but it saves blank image((
You can do something like that:
var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
encoder.Frames.Add(BitmapFrame.Create(yourImage));
using (var stream = dlg.OpenFile())
{
encoder.Save(stream);
}
BTW, there is a SaveFileDialog in WPF too, you don't have to use the one from Windows Forms
For WPF code will be like :
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
if (dlg.ShowDialog() == true)
{
var encoder = new JpegBitmapEncoder(); // Or PngBitmapEncoder, or whichever encoder you want
encoder.Frames.Add(BitmapFrame.Create(bi));
using (var stream = dlg.OpenFile())
{
encoder.Save(stream);
}
}
Here bi is the BitmapImage

Categories