C# How to upload any file to a fileuploader? - c#

I need upload my file to "https://file.io" and i tried this:
`private void buttonInput_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
var resStr = client.UploadFile("https://file.io", #"C:\data\test.txt");
var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
var linkToFile = jObjResult["link"];
}
}`
It does upload target txt file to url.
But im taking that error:
Severity Code Description Project File Line Hide Status
Error CS01 'JObject' scope valid03
How to Fix it?
Btw im using them:
using System;
using System.Net;
using System.Text;
using System.Collections.Generic;

Related

System.UnauthorizedAccessException C# Windows 10 Phone Emulator

I know there is a bunch of threads on seemingly the same issue but I cannot for the life of me figure this out after 3 hours so I really need some help.
I understand that I am getting this error because the system does not have access to the file. I have tried setting permissions to full and a few other code snippets to solve my issue but none have worked.
This is a windows 10 app using Xaramin,
I am trying to populate a listbox with contact from an XML file. I have the list box itemsSource set to "Data Context" and path "myList". The XML build action is set to "Content" and the Copy to Output Directory Set to "Copy Always".
I have attempted to follow the tutorial from my course from the beginner 3 times and always get the same error.
Here is the error I am getting
Below is the entire code on the page.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Xml;
using System.Xml.Linq;
using Windows.Storage;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace ContactsApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
string TEMPFILEPATH = "";
string TARGETFILEPATH = "";
private ObservableCollection<string> lstd = new ObservableCollection<string>();
public ObservableCollection<string> myList { get { return lstd; } }
public MainPage()
{
this.InitializeComponent();
}
private void Grid_Loading(FrameworkElement sender, object args)
{
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
StorageFolder installedLocation = package.InstalledLocation;
StorageFolder targetLocation = ApplicationData.Current.LocalFolder;
TEMPFILEPATH = installedLocation.Path.ToString() + "\\Contacts.xml";
TARGETFILEPATH = targetLocation.Path.ToString() + "\\Contacts.xml";
File.Move(TEMPFILEPATH, TARGETFILEPATH);
loadContacts();
}
private void loadContacts()
{
XmlReader xmlReader = XmlReader.Create(TARGETFILEPATH);
while (xmlReader.Read())
{
if (xmlReader.Name.Equals("ID") && (xmlReader.NodeType == XmlNodeType.Element))
{
lstd.Add(xmlReader.ReadElementContentAsString());
}
}
DataContext = this;
xmlReader.Dispose();
}
}
}
I will be eternally grateful for any help regarding the matter. :)
You should not try to access restricted paths in constrained environments (like Windows Phone).
Instead, if you really need to embed this file with your application, change the build action to Embedded Resource and to Do not copy for your xml file, and then retrieve the resource inside your code as an Embedded Resource:
public void LoadContacts()
{
const string fileName = "Contacts.xml";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
var path = assembly.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase));
if(path == null)
throw new Exception("File not found");
using (var stream = assembly.GetManifestResourceStream(path))
using (var reader = XmlReader.Create(stream))
{
while (reader.Read())
{
if (reader.Name.Equals("ID") && (reader.NodeType == XmlNodeType.Element))
{
lstd.Add(reader.ReadElementContentAsString());
}
}
}
DataContext = this; // better to move this inside the constructor
}

How to get output of http request in JSON file?

I am making a http get request to a url and I am able to get data from that web page but I am not able to store it in JSON format and also not able to interpret data and get the required data.I am using ASP.NET and C# for it.
This is code for my CS file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace httprequest_web
{
public partial class req : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string baseu = "http://railenquiry.in/runningstatus/";
string url = string.Concat(baseu, TextBox1.Text);
var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
request.ContentType = "application/json; charset=utf-8";
text = sr.ReadToEnd();
}
Label1.Text = text;
}
catch
{
Label1.Text = "No Data Found";
}
}
}
}
and screenshot of output I am receiving is:
I want to take output in a well structured JSON file and only want name of station, time of arrival and time of departure in it. Please tell me how to do it?
Take a look at this project : HtmlAgilityPack But you need to ask the owner of the website before using his data
The URL you're requesting is just a normal web page, it doesn't return JSON.
You'll need to scrape the response, in order to do what you want.
Take a look at this question for examples using HtmlAgilityPack:
Parsing HTML Table in C#

Adding text to an email using an Outlook addin C# 2010

I want to add some text to the body of my email. But i keep getting this error:
Error 1 'EmailHelper.EmailHelperRibbon' does not contain a definition for 'Application' and no extension method 'Application' accepting a
first argument of type 'EmailHelper.EmailHelperRibbon' could be found
(are you missing a using directive or an assembly reference?)
My code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
namespace EmailHelper
{
public partial class EmailHelperRibbon
{
private void EmailHelperRibbon_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
System.Windows.Forms.MessageBox.Show("Your Ribbon Works!");
Microsoft.Office.Interop.Outlook.MailItem mailItem = (Microsoft.Office.Interop.Outlook.MailItem)
this.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
{
mailItem.Subject = "This text was added by using code";
mailItem.Body = "This text was added by using code";
}
}
}
}
Try this one:
var inspector = this.Context as Outlook.Inspector;
var currentMailItem = inspector.CurrentItem as Outlook.MailItem;
currentMailItem.Body = "your text";
I am guessing this is a Ribbon based on the name, so you need to access the application off of the Globals class:
Globals.ThisAddIn.Application.CreateItem(...)

How to give Common path to video

I am working in project in which I have used vlc plugin v2. the path for my video is
axVLC.playlist.add(#"D:\My Project\Science\Resources\myvideo.mp4");
axVLC.playlist.play();
now the problem is when I build the project and give it to someone and he/she install it on his/her computer , it show exception that video path is wrong. I am sure that path is not suitable as my the video path in my project is D:... and he/she installed it on C.
So my question is that is there any way to give it common path by which user don`t face such kind of error
Import IO
Using System.IO;
then declare a string that will reference to your video folder
string AbsoluteRef;
use this code in your form load
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
Now declare a string for your video or which ever file like
string vlcvideo;
now add the two together
vlcvideo = AbsoluteRef & "myvideo.mp4";
Finnally add all this into your vlc plugin
axVLC.playlist.add(vlcvideo);
Complete Code looks like so.
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
using yournamespace.Forms;
using System.IO;
namespace yourNameSpace
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string AbsoluteRef = null;
private void frmMain_Load(object sender, EventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
string vlcVideo = AbsoluteRef + "myvideo.mp4";
axVLC.playlist.add(vlcvideo);
}

Getting (The name 'file' does not exist in the current context) message

UPDATE 1:
Here is the full code behind from the downloaded example, unedited:
using System;
using System.IO;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String UpPath;
UpPath = "C:\\UploadedUserFiles";
if (!Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\UploadedUserFiles\\");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = file;
if (upload.ContentLength == 0)
continue;
string c = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name.
try
{
upload.SaveAs("C:\\UploadedUserFiles\\" + c);
Span1.InnerHtml = "Upload(s) Successful.";
}
catch(Exception Exp)
{
Span1.InnerHtml = "Upload(s) FAILED.";
}
}
}
}
ORIGINAL QUESTION:
I've just downloaded a "file uploading" example from www.asp.net:
Link to tutorial: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-multiple-file-uploads-in-aspnet-2
Link to download: http://download.microsoft.com/download/8/6/9/869ff08a-1e39-4bab-a303-f7dcedc52427/CS-ASP-MultiFileUpload-CS.zip
and copied the files to my webserver after extracting them.
When I navigate to http://server/uploader/Default.aspx
It creates the folder in the servers c drive successfully, but on the web browser I get the following error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'file' does not exist in the current context
Source Error:
Line 29: for (int i = 0; i < uploads.Count; i++)
Line 30: {
Line 31: HttpPostedFile upload = file;
Line 32:
Line 33: if (upload.ContentLength == 0)
Source File: c:\Inetpub\wwwroot\uploader\Default.aspx.cs Line: 31
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3623; ASP.NET Version:2.0.50727.3618
Anyone know why this is happening?
You are addressing an undeclared local variable file, you should be retrieving the HttpPostedFile from the uploads "Items" collection using the Item index;
HttpPostedFile upload = uploads[i];
It seems a bug on the sample code. Try replacing this
HttpPostedFile upload = file
by
HttpPostedFile upload = uploads[i]
Along with "Default.aspx" and "Default.aspx.cs", you need "Default.aspx.Designer.cs" File.
As all the controls are defined with its style in "Designer" file.

Categories