Saving File with selectable extensions - c#

So I made code again about saving files (you can select file name)
here:
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
}
the problem is I want to have 2 selectable extensions:
-.txt
-.md
because the code I wrote can save to any type of file(and if you didn't put anything I will save as . FILE) and I just want only 1 save file type.
Save dialog

You need to set the dialog's Filter property according to the pattern:
Text to show|Filter to apply|Text to show 2|Filter to apply 2|...
For example in your case, where you seem to be saying you want the save dialog to have a combo dropdown containing two things, one being Text and the other being Markdown, your Filter has 4 things:
.Filter = "Text files|*.txt|Markdown files|*.md";
It is typical to put the filter you will apply into the text you will show too, so the user can see what you mean by e.g. "Text files" but I've left that out for clarity.
For example you might choose to make it say Text files(*.txt)|*.txt - the text in the parentheses has no bearing on the way the filter works, it's literally just shown to the user, but it tells them "files with a .txt extension"
Footnote, you may have to add some code that detects the extension from the FileName if you're saving different content per what the user chose e.g.:
var t = Path.GetExtension(saveFileDialog.FileName);
if(t.Equals(".md", StringComparison.OrdinalIgnoreCase))
//save markdown
else
//save txt

You can just use the filter of your dialog to set the allowed extensions:
// Filter by allowed extensions
saveFileDialog1.Filter = "Allowed extensions|*.txt;*.md";

Related

How to save file in C# on RichTextBox with keyboard shorcut

I am writing the code editor in C# and i want to make the saving with keyboard shorcut CTRL + S this is my saving file code
private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
{
var di = new SaveFileDialog();
di.Filter = "Text Files|*.txt";
di.FileName = "Txt" + ".txt";
var result = di.ShowDialog();
if (result == DialogResult.OK)
{
File.WriteAllText(di.FileName, textBox1.Text);
}
}
I want the tip how to solve it or piece of code that will work.
Select the Save menu strip item:
Open the properties window and set the keyboard shortcut:
Note that your code is only saving the rich text (rich = formatted) as plain text, so your file will not have that formatting. If you want to save as rich text, use
richTextBox1.SaveFile("whatever.rtf");

How do I use the variable of the selected folder?

When i select a folder manually, through FolderBrowserDialog, my need to substitute the path to the code below.
Where "%ProgramFiles (x86)%\MyApp" must be replaced with the variable of the selected folder + file name.
As a result, when selecting a folder, the file size "testFile.txt" in "label1" should be displayed (there will be two or more such files).
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
DialogResult result = folderBrowser.ShowDialog();
if (result == DialogResult.OK)
{
// Determine the size of the file in KB (dividing the number of bytes by 1024)
FileInfo fs1 = new FileInfo(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%\\MyApp\\testFile.txt"));
long FileSize1 = fs1.Length / 1024;
label1.Text = "testFile.txt (" + Convert.ToString(FileSize1) + " KB)";
if (FileSize1 > 180 & FileSize1 < 186) // If the file is larger and smaller than the specified sizes
{
label1.ForeColor = Color.Green;
}
else
{
label1.ForeColor = Color.Red;
}
}
}
Decision, edit:
FileInfo fs1 = new FileInfo(folderBrowser.SelectedPath + "\\testFile.txt");
or
FileInfo fs1 = new FileInfo(Path.Combine(folderBrowser.SelectedPath, "testFile.txt"));
The official documentation has an item dedicated specifically to this: How to: Choose Folders with the Windows Forms FolderBrowserDialog Component
To choose folders with the FolderBrowserDialog component
In a procedure, check the FolderBrowserDialog component's DialogResult property to see how the dialog box was closed and get the
value of the FolderBrowserDialog component's SelectedPath property.
If you need to set the top-most folder that will appear within the tree view of the dialog box, set the RootFolder property, which takes
a member of the Environment.SpecialFolder enumeration.
Additionally, you can set the Description property, which specifies the text string that appears at the top of the
folder-browser tree view.
In the example below, the FolderBrowserDialog component is used to
select a folder, similar to when you create a project in Visual Studio
and are prompted to select a folder to save it in. In this example,
the folder name is then displayed in a TextBox control on the form. It
is a good idea to place the location in an editable area, such as a
TextBox control, so that users may edit their selection in case of
error or other issues. This example assumes a form with a
FolderBrowserDialog component and a TextBox control.
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
}
According to that example, you can get a string to the chosen folder using folderBrowser.SelectedPath.

How Do I use Drag And Drop To Export A File (C#)

I am currently using a file dialog to export a file, but I was wondering how I could export my file using drag and drop. I couldn't figure out how to get the file path of where the item is being dropped. Here is the code that I used for open file dialogue in case its required.
if (this.listView1.SelectedItems.Count > 0)
{
ListViewItem item = this.listView1.SelectedItems[0];
string text = this.faderLabel8.Text;
if (!text.EndsWith(#"\"))
{
text = text + #"\";
}
using (SaveFileDialog dialog = new SaveFileDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
{
Jtag.ReceiveFile(item.SubItems[0].Text, text + item.SubItems[0].Text);
}
}
}
You don't need the path of where the file is being dropped. Instead you need to create a temporary file.
Save file to a temporary folder
Initiate drag on an event/command, such as mouse down, in the following way:
//(This example is uses WPF/System.Windows.DragDrop)
//Create temporary file
string fileName = "DragDropSample.txt";
var tempPath = System.IO.Path.GetTempPath();
var tempFilePath = System.IO.Path.Combine(tempPath, fileName);
System.IO.File.WriteAllText(tempFilePath, "Testing drag and drop");
//Create DataObject to drag
DataObject dragData = new DataObject();
dragData.SetData(DataFormats.FileDrop, new string[] { tempFilePath });
//Initiate drag/drop
DragDrop.DoDragDrop(dragSourceElement, dragData, DragDropEffects.Move);
For WinForms example and more details see:
Implement file dragging to the desktop from a .net winforms application?
If you want it to be useful through "drag and drop" you would require some sort of graphical interface that displays the files in a container where they are and then another container to where you want to move them. When you highlight an item with your mouse you add them to your itemList and when your drop them you copy them. Just make sure the List is emptied once in case you remove the highlight.

Scrolling list with multiple objects

I have been making a form to let the user save his progress. There are 6 virtual slots which contain different save files read from a folder. I want to have the same set up just with a scrollbar to let user scroll through save files, in case he has more than 6 made.
The set up is: picturebox which loads save file when clicked, label for file name and for file date, picturebox to delete the save file, and a panel underneath to save file when the slot is clicked.
Below is the code I use to load in 6 save files. (I will get the date by reading the save file start as it contains the date, but I have not done that part yet).
private void loadsavestoscreen()
{
string filename;
string extension;
string locpath = #"C:\test";
String[] allfiles = System.IO.Directory.GetFiles(locpath, "*.*", System.IO.SearchOption.TopDirectoryOnly);
int counter = 0;
foreach (String file in allfiles)
{
if (counter == 6 || counter == allfiles.Length - 1)
{ labelcheck(); break; }
if ((extension = Path.GetExtension(file)) == ".dat")
{
filename = Path.GetFileNameWithoutExtension(file);
//Console.WriteLine(filename);
changelbl(counter, filename);
counter++;
}
}
}
'labelcheck' checks if the text is correct, if not it hides the label.
'lblchange' changes the name of the label on the correct slot.
My question is: How would I implement a scrollbar to allow the user to scroll through more save files when there is more than 6?
Here's a snippet of the form:
I am slightly new to programming so my apologies if I've made some obvious errors. Thanks for any help.
Without a list object or a container this is not very easy to solve.
I suggest you to use a DataGridView or a ListView object. You can easily add your file entries as objects to these lists. They have an option Scrollable, which you can set true or false.
I would also create a class for that save file entries (storing label/image position and contents) and add them to your DataGridView or ListView.
If you want to know how to add images to those controls:
How do add image to System.Windows.Forms.ListBox?

How to replace some text with picture in RichTextBox without clipboard? [duplicate]

Most of the examples I see say to put it on the clipboard and use paste, but that doesn't seem to be very good because it overwrites the clipboard.
I did see one method that manually put the image into the RTF using a pinvoke to convert the image to a wmf. Is this the best way? Is there any more straightforward thing I can do?
The most straightforward way would be to modify the RTF code to insert the picture yourself.
In RTF, a picture is defined like this:
'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}'
A question mark indicates the control word is optional.
"data" is simply the content of the file in hex format. If you want to use binary, use the \bin control word.
For instance:
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}
\pict = starts a picture group,
\pngblip = png picture
\picwX = width of the picture (X is the pixel value)
\pichX = height of the picture
\picwgoalX = desired width of the picture in twips
So, to insert a picture, you just need to open your picture, convert the data to hex, load these data into a string and add the RTF codes around it to define a RTF picture. Now, you have a self contained string with picture data which you can insert in the RTF code of a document. Don't forget the closing "}"
Next, you get the RTF code from your RichTextBox (rtbBox.Rtf), insert the picture at the proper location, and set the code of rtbBox.Rtf
One issue you may run into is that .NET RTB does not have a very good support of the RTF standard.
I have just made a small application* which allows you to quickly test some RTF code inside a RTB and see how it handles it. You can download it here:
RTB tester (http://your-translations.com/toys).
You can paste some RTF content (from Word, for instance) into the left RTF box and click on the "Show RTF codes" to display the RTF codes in the right RTF box, or you can paste RTF code in the right RTB and click on "Apply RTF codes" to see the results on the left hand side.
You can of course edit the codes as you like, which makes it quite convenient for testing whether or not the RichTextBox supports the commands you need, or learn how to use the RTF control words.
You can download a full specification for RTF online.
NB It's just a little thing I slapped together in 5 minutes, so I didn't implement file open or save, drag and drop, or other civilized stuff.
I use the following code to first get the data from clipboard, save it in memory, set the image in clipboard, paste it in Rich Text Box and finally restore the data in Clipboard.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All files |*.*"
OpenFileDialog1.Multiselect = True
Dim orgdata = Clipboard.GetDataObject
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each fname As String In OpenFileDialog1.FileNames
Dim img As Image = Image.FromFile(fname)
Clipboard.SetImage(img)
RichTextBox1.Paste()
Next
End If
Clipboard.SetDataObject(orgdata)
End Sub
The OpenFileDailog1, RichTextBox1 and Button1 are Open File Dialog, Rich Text Box and button controls respectively.
private void toolStripButton1_Click(object sender, EventArgs e)
{
FileDialog fDialog = new OpenFileDialog();
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
fDialog.RestoreDirectory = true;
fDialog.Title = "Choose file to import";
if (fDialog.ShowDialog() == DialogResult.OK)
{
string lstrFile = fDialog.FileName;
Bitmap myBitmap = new Bitmap(lstrFile);
// Copy the bitmap to the clipboard.
Clipboard.SetDataObject(myBitmap);
DataFormats.Format format = DataFormats.GetFormat(DataFormats.Bitmap);
// After verifying that the data can be pasted, paste
if(top==true && this.rtTop.CanPaste(format))
{
rtTop.Paste(format);
}
if (btmLeft == true && this.rtBottomLeft.CanPaste(format))
{
rtBottomLeft.Paste(format);
}
if (btmCenter == true && this.rtBottomCenter.CanPaste(format))
{
rtBottomCenter.Paste(format);
}
if (btmRight == true && this.rtBottomRight.CanPaste(format))
{
rtBottomRight.Paste(format);
}
}
}
Here is what I do to hack the rich text control:
Insert the required image in wordpad or MS-WORD. Save the file as 'rtf'. Open the rtf file in notepad to see the raw rtf code. Copy the required tags & stuff to the 'rtf' property of your Rich Text Box (append to existing text).
There is some trial and error involved but works.
With C#, I use place holder StringBuilder objects with the necessary rtf code. Then I just append the image path.
This is a workaround for not having to learn the RTF syntax.
My own version that I posted in a new thread, apparently I should have searched and posted it here. Anyway, using the clipboard again, very easy.
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Images |*.bmp;*.jpg;*.png;*.gif;*.ico";
openFileDialog1.Multiselect = false;
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Image img = Image.FromFile(openFileDialog1.FileName);
Clipboard.SetImage(img);
richTextBox1.Paste();
richTextBox1.Focus();
}
else
{
richTextBox1.Focus();
}
}
}
If you were in C++, the way to do it is thru OLE. More specifically, if you search Google for ImageDataObject it will show C++ code how to insert a HBITMAP into the RTF Control. One link is here.
Now, how this translates into .Net code, I don't know. I currently don't have the time to work thru the details.
I was also looking for something for this same task and found this ->
http://sourceforge.net/projects/netrtfwriter/
You can generate any type of RTF text that you would want and then use it however you wish. Very well structured example which will auto sense the image type being used (jpg/jpeg/png etc) and worked for the image files I have been using. If you are in a hurry then this is a great RTF generator!
All I did was make a small pictureBox control in c# and made sure it was hidden behind another object big enough to hide it. Then I made a button to insert a picture, and it loaded the pictureBox with the image then it puts it in the richTextBox then it clears the pictureBox control.
Here is the code.
private void InsertPicture_Click(object sender, EventArgs e)
{
{
if (openFileDialog4.ShowDialog() == DialogResult.OK)
{
// Show the Open File dialog. If the user clicks OK, load the
// picture that the user chose.
pictureBox2.Load(openFileDialog4.FileName);
Clipboard.SetImage(pictureBox2.Image);
pictureBox2.Image = null;
this.richTextBox1.Paste();
}
}
}
After inserting the code to do it with the clipboard, type in Clipboard.Clear();. It works well and it doesn't clear everything, only the item last added to the clipboard.
Full Code:
private void addPictureToRTB()
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Pictures|*.png" })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
ClipBoard.SetImage(Image.FromFile(ofd.FileName));
richTextBox.Paste();
Clipboard.Clear();
}
}
}
Then reference this function where you need to.
Several hours surfing for solution to insert image without loosing quality and fixed the gray background with transparent image/png
// assuming the image is in your Resources
var img = Resources.ImageWithTransparentBckgrnd;
var g = Graphics.FromImage(img);
using (var ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Png);
IntPtr ipHdc = g.GetHdc();
Metafile mf = new Metafile(ms, ipHdc);
g = Graphics.FromImage(mf);
g.FillEllipse(Brushes.White, 0, 0, 16, 16); // size you want to fill in
g.Dispose();
mf.Save(ms, ImageFormat.Png);
IDataObject dataObject = new DataObject();
dataObject.SetData("PNG", false, ms);
Clipboard.SetDataObject(dataObject, false);
richTextBox1.Paste();
SendKeys.Send("{RIGHT}");
richTextBox1.Focus();
}

Categories

Resources