How to upload a file in window forms? [closed] - winforms

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Not suitable for this site
In window forms, how to upload a file, I did not found any file upload control. Can you give me any reference? I want to store the document with in my systems drive. Thank you.

You can put on your form button and create click handler to it with the following code:
private void buttonGetFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Text files | *.txt"; // file types, that will be allowed to upload
dialog.Multiselect = false; // allow/deny user to upload more than one file at a time
if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK
{
String path = dialog.FileName; // get name of file
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
{
// ...
}
}
}

You should use OpenFileDialog, here is a link:
http://msdn.microsoft.com/en-us/library/aa984392%28v=vs.71%29.aspx

Please refer to this tutorial for raw HTTP POST:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Reference to WebClient class of .NET:
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx
A simple HTTP POST can be done like this:
string Upload_File_Content = ...;
string Url = ...;
using (var Http_Client = new WebClient()) {
var Post_Data = new NameValueCollection();
Post_Data["upload_file"] = Upload_File_Content;
var Response = Http_Client.UploadValues(Url,"POST",Post_Data);
}

Related

C# WPF - How to Save a Screenshot of your Program's Interface's Current View?

I am trying to have an option in my program called 'Save Current Snapshot', where a picture of my program's interface is saved to a desired location. This is for reference purposes, e.g. if someone doesn't want to open the program to see a result they've already gathered.
I already have a program screenshot function, I just don't know how to implement it with a SaveFileDialog to save the image.
Screenshot function:
private static BitmapSource CopyScreen()
{
using (var screenBmp = new Bitmap(
(int)SystemParameters.PrimaryScreenWidth,
(int)SystemParameters.PrimaryScreenHeight,
System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (var bmpGraphics = Graphics.FromImage(screenBmp))
{
bmpGraphics.CopyFromScreen(0, 0, 0, 0, screenBmp.Size);
return Imaging.CreateBitmapSourceFromHBitmap(
screenBmp.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
}
}
SaveFileDialog code:
SaveFileDialog saveImage = new SaveFileDialog();
saveImage.Filter = "Images|*.png;*.bmp;*.jpg";
saveImage.ShowDialog();
Could someone please help me out with saving the image to a user-chosen location?
Thanks.
You can use the referenced code in the comment.
Use the save dialog to get the desired path and do just like commented by #Zack
// If the file name is not an empty string open it for saving.
if(saveImage.FileName != "")
{
System.IO.FileStream fs = System.IO.File.Open(saveImage.FileName, System.IO.FileMode.OpenOrCreate);
Screenshot.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp);
fs.Close();
}
I'm on the phone so can't check this, comment if you have problems

WPF native windows 10 toasts

Using .NET WPF and Windows 10, is there a way to push a local toast notification onto the action center using c#? I've only seen people making custom dialogs for that but there must be a way to do it through the os.
You can use a NotifyIcon from System.Windows.Forms namespace like this:
class Test
{
private readonly NotifyIcon _notifyIcon;
public Test()
{
_notifyIcon = new NotifyIcon();
// Extracts your app's icon and uses it as notify icon
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
// Hides the icon when the notification is closed
_notifyIcon.BalloonTipClosed += (s, e) => _notifyIcon.Visible = false;
}
public void ShowNotification()
{
_notifyIcon.Visible = true;
// Shows a notification with specified message and title
_notifyIcon.ShowBalloonTip(3000, "Title", "Message", ToolTipIcon.Info);
}
}
This should work since .NET Framework 1.1. Refer to this MSDN page for parameters of ShowBalloonTip.
As I found out, the first parameter of ShowBalloonTip (in my example that would be 3000 milliseconds) is generously ignored. Comments are appreciated ;)
I know this is an old post but I thought this might help someone that stumbles on this as I did when attempting to get Toast Notifications to work on Win 10.
This seems to be good outline to follow -
Send a local toast notification from desktop C# apps
I used that link along with this great blog post- Pop a Toast Notification in WPF using Win 10 APIs
to get my WPF app working on Win10. This is a much better solution vs the "old school" notify icon because you can add buttons to complete specific actions within your toasts even after the notification has entered the action center.
Note- the first link mentions "If you are using WiX" but it's really a requirement. You must create and install your Wix setup project before you Toasts will work. As the appUserModelId for your app needs to be registered first. The second link does not mention this unless you read my comments within it.
TIP- Once your app is installed you can verify the AppUserModelId by running this command on the run line shell:appsfolder . Make sure you are in the details view, next click View , Choose Details and ensure AppUserModeId is checked. Compare your AppUserModelId against other installed apps.
Here's a snipit of code that I used. One thing two note here, I did not install the "Notifications library" mentioned in step 7 of the first link because I prefer to use the raw XML.
private const String APP_ID = "YourCompanyName.YourAppName";
public static void CreateToast()
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("This is my title!!!!!!!!!!"));
stringElements[1].AppendChild(toastXml.CreateTextNode("This is my message!!!!!!!!!!!!"));
// Specify the absolute path to an image
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Your Path To File\Your Image Name.png";
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
imageElements[0].Attributes.GetNamedItem("src").NodeValue = filePath;
// Change default audio if desired - ref - https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-audio
XmlElement audio = toastXml.CreateElement("audio");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Reminder");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.IM");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Mail"); // sounds like default
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call7");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call2");
//audio.SetAttribute("loop", "false");
// Add the audio element
toastXml.DocumentElement.AppendChild(audio);
XmlElement actions = toastXml.CreateElement("actions");
toastXml.DocumentElement.AppendChild(actions);
// Create a simple button to display on the toast
XmlElement action = toastXml.CreateElement("action");
actions.AppendChild(action);
action.SetAttribute("content", "Show details");
action.SetAttribute("arguments", "viewdetails");
// Create the toast
ToastNotification toast = new ToastNotification(toastXml);
// Show the toast. Be sure to specify the AppUserModelId
// on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
}
UPDATE
This seems to be working fine on windows 10
https://msdn.microsoft.com/library/windows/apps/windows.ui.notifications.toastnotificationmanager.aspx
you will need to add these nugets
Install-Package WindowsAPICodePack-Core
Install-Package WindowsAPICodePack-Shell
Add reference to:
C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd
And
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
And use the following code:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
for (int i = 0; i < stringElements.Length; i++)
{
stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));
}
// Specify the absolute path to an image
string imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png");
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Toast Sample").Show(toast);
The original code can be found here: https://www.michaelcrump.net/pop-toast-notification-in-wpf/
I managed to gain access to the working API for windows 8 and 10 by referencing
Windows.winmd:
C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral
This exposes Windows.UI.Notifications.
You can have a look at this post for creating a COM server that is needed in order to have notifications persisted in the AC with Win32 apps https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/10/16/quickstart-handling-toast-activations-from-win32-apps-in-windows-10/.
A working sample can be found at https://github.com/WindowsNotifications/desktop-toasts

XAML OpenFileDialog(), missing namespace

I recently started doing some WPF windows 8.1 apps and now I searched for a open file dialog. Some information is available at Microsoft and some blogs but the results are not that great.
Tried these lines:
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
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
This should work greatly as there are way more examples like this one, unfortunately not in my case because of the missing assembly reference.. It does not know Win32 in the Microsoft using.
If in any way someone can clear this out to me, I would appreciate it.

Sharepoint 2010 Upload file using Silverlight 4.0

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu
Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Display a PDF in WPF Application [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Any ideas how to display a PDF file in a WPF Windows Application?
I am using the following code to run the browser but the Browser.Navigate method does not do anything!
WebBrowser browser = new WebBrowser();
browser.Navigate("http://www.google.com");
this.AddChild(browser); // this is the System.Windows.Window
You can get the Acrobat Reader control working in a WPF app by using the WindowsFormHost control. I have a blog post about it here:
http://hugeonion.com/2009/04/06/displaying-a-pdf-file-within-a-wpf-application/
I also have a 5 minute screencast of how I made it here:
http://www.screencast.com/t/JXRhGvzvB
You could simply host a Web Browser control on the form and use it to open the PDF.
There's a new native WPF "WebBrowser" control in .NET 3.51, or you could host the Windows.Forms browser in your WPF app.
Oops. this is for a winforms app. Not for WPF. I will post this anyway.
try this
private AxAcroPDFLib.AxAcroPDF axAcroPDF1;
this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();
this.axAcroPDF1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axAcroPDF1.Enabled = true;
this.axAcroPDF1.Name = "axAcroPDF1";
this.axAcroPDF1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axAcroPDF1.OcxState")));
axAcroPDF1.LoadFile(DownloadedFullFileName);
axAcroPDF1.Visible = true;
Try MoonPdfPanel - A WPF-based PDF viewer control
http://www.codeproject.com/Articles/579878/MoonPdfPanel-A-WPF-based-PDF-viewer-control
GitHub: https://github.com/reliak/moonpdf
Just use a frame and a webbrowser like so
Frame frame = new Frame();
WebBrowserbrowser = new WebBrowser();
browser.Navigate(new Uri(filename));
frame.Content = browser;
Then when you don't need it anymore do this to clean it up:
WebBrowser browser = frame.Content as WebBrowser;
browser.Dispose();
frame.Content = null;
If you don't clean it up then you might have memory leak problems depending on the version of .NET your using. I saw bad memory leaks in .NET 3.5 if I didn't clean up.
The following code expects Adobe Reader to be installed and the Pdf extension to be connected to this.
It simply runs it:
String fileName = "FileName.pdf";
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = fileName;
process.Start();
process.WaitForExit();
Disclosure: Here is a commercial one and I work for this company.
I realize that an answer has already been accepted but the following does not require Adobe Reader/Acrobat and it is a WPF solution - as opposed to Winforms. I also realize this is an old question but it has just been updated so I guess it is still actual.
PDFRasterizer.NET 3.0 allows you to render to a WPF FixedDocument. It preserves all vector graphics (PDF graphics are converted to more or less equivalent WPF elements. This is probably closest to what you need.
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
pdfDoc = new Document(file);
ConvertToWpfOptions convertOptions = new ConvertToWpfOptions();
RenderSettings renderSettings = new RenderSettings();
...
FixedDocument wpfDoc = pdfDoc.ConvertToWpf(renderSettings, convertOptions, 0, 9, summary);
}
You can pass the wpfDoc to e.g. the WPF DocumentViewer to quickly implement a viewer.
You can also use FoxitReader. It's free and comes with an ActiveX control that registers in the web browsers (IE and others) after you install the FoxitReader application.
So after you install FoxitReader on the system put a WebBrowser Control and set its Source property to point to the file path of your PDF file.
Check this out: http://itextsharp.sourceforge.net/
You may have to use a WindowsFormsHost, but since it is open source, you might be able to make it a little more elegant in WPF.

Resources