C# How to load a Canvas with XML - c#

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);

Related

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)];

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

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();
}
}
}

Encoding and Decoding excel file as Base64 string

This is for a Windows Console App
I am saving an Excel file that I am using as a template for reports as a Base64 string. using the code below to encode the file as a base64 string. I then store it in an SQL Database as NVARCHAR(MAX)
Stream myStream = null;
string base64String;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
MemoryStream ms = new MemoryStream();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
using (myStream)
{
myStream.CopyTo(ms);
byte[] excelBytes = ms.ToArray();
base64String = Convert.ToBase64String(excelBytes, Base64FormattingOptions.None);
FileNameTxt.Text = openFileDialog1.FileName;
}
I then retrieve this file and decode the string and create a ClosedXML excel file.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
StoredFile = reader["StoredFile"].ToString();
}
reader.Close();
wb = workBook(StoredFile);
}
public static XLWorkbook workBook(string File)
{
byte[] data = System.Convert.FromBase64String(File);
MemoryStream ms = new MemoryStream(data);
XLWorkbook wb = new XLWorkbook(ms);
return wb;
}
The problem is that the end result is a workbook that has lost some of its formatting. mainly appears to have only affected border formatting.
I don't know if it is an issue with the encoding, decoding or generation of new file using ClosedXML that is causing the issue. Any direction or thoughts are greatly appreciated.

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

how i pass image in This function

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog(); // Show open file dialog box
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
txtBrowse.Text = filename;
}
ImageSource imageSource = new BitmapImage(new Uri(txtBrowse.Text));
imgImageAdlut.Source = imageSource; ;
byte[] array1 = null;
//array1 = imageToByteArray();
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
Try this:
var img = new System.Drawing.Bitmap(#"D:\Your image path\your image.bmp");
byte[] array1 = imageToByteArray(img);

Categories