I'm sending the contents of a few textboxes to my website using the HttpClient. My PHP script inserts the data in a database.
But after clicking the btnSubmit-button, it runs the code but nothing is added to my database and no exceptions are thrown. What's wrong with my code?
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Net.Http;
namespace PhoneApp2
{
public partial class Submit2 : PhoneApplicationPage
{
public Submit2()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("barcode", out parameter))
{
Barcode.Text = parameter;
}
}
public static int typeConnection()
{
switch (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType)
{
default:
return 0;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
return 1;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
return 2;
}
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
try
{
if (typeConnection() < 2)
{
string URI = "http://cocktailpws.net23.net/requests/add_contribution.php";
string myParameters = "barcode=" + Barcode.Text + "&booze=" + Name.Text + "&email=" + Email.Text;
sendData(URI, myParameters);
}
else
{
MessageBox.Show("No database connection could be established. Please check your internet connection and try again.");
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
public async void sendData(string URI, string myParameters)
{
using (HttpClient hc = new HttpClient())
{
var response = await hc.PostAsync(URI, new StringContent(myParameters));
}
}
}
}
PHP:
if(isset($_POST['barcode']) && isset($_POST['booze']) && isset($_POST['email'])){
include_once "../inc/inc_db.php";
$booze = sqlesc($_POST['booze']);
$barcode = sqlesc($_POST['barcode']);
$email = sqlesc($_POST['email']);
date_default_timezone_set('Europe/Amsterdam');
$date = date("Y-m-d H:i:s");
$query = "INSERT INTO contr_barcode(booze,barcode,email,datum) VALUES ('$booze','$barcode','$email',$date')";
if(mysqli_query($con,$query)){
echo "1";
}else{
echo "0";
}
}
You are sending the values formatted as if you are sending application/x-www-form-urlencoded however, by default StringContent will declare the content-type as text/plain. It is possible that the PHP framework is not parsing the content correctly because it thinks you are just sending unformatted plain text.
You could either change the content-type of the StringContent object, or you could use the UrlEncodedFormContent class. e.g.
var content = new StringContent(myParameters);
content.Headers.Content-Type = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await hc.PostAsync(URI, content);
Related
I try to write a UDP-Chat in C#.
I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them.
I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving.
is there a error in my code or is it a desing error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;
namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
string name = "testuser";
UdpClient receiveClient = new UdpClient(1800);
IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
public Chat_window(string name)
{
this.name = name;
fileWriter("Chat started", false); // write the initial start date in the errorfile
InitializeComponent();
Message_Load(); // starts the listen server theread
}
private void Message_Load()
{
lb_chat.Items.Add(name + " Joined the room...");
Thread rec = new Thread(ReceiveMessageFn);
rec.Start();
}
private void ReceiveMessageFn()
{
try
{
while (true)
{
Byte[] receve = receiveClient.Receive(ref receiveEndPint);
string message = Encoding.UTF8.GetString(receve);
if (message == name + " logged out...")
{
break;
}
else
{
if (message.Contains(name + " says >>"))
{
message = message.Replace(name + " says >>", "Me says >>");
}
ShowMessage(message);
}
}
//Thread.CurrentThread.Abort();
//Application.Current.Shutdown();
}
catch (Exception e)
{
//errorHandler(e);
}
}
private void ShowMessage(string message)
{
if (lb_chat.Dispatcher.CheckAccess())
{
lb_chat.Items.Add(message);// add Item to list-box
lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
lb_chat.UpdateLayout();
}
else {
lb_chat.Dispatcher.BeginInvoke(
new Action<string>(ShowMessage), message); // if list-box is not access able get access
return;
}
}
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
{
tb_eingabe.Text = "";
}
private void btn_submit_Click(object sender, RoutedEventArgs e)
{
submit_message();
}
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
submit_message();
}
}
void submit_message()
{
if (tb_eingabe.Text != "")
{
string data = name + " says >> " + tb_eingabe.Text;
SendMessage(data);
tb_eingabe.Clear(); // clear the textbox-values
tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
}
}
private void SendMessage(string data)
{
try{
UdpClient sendClient = new UdpClient();
Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
sendClient.Send(message, message.Length, endPoint);
sendClient.Close();
}
catch (Exception e)
{
errorHandler(e);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string data = name + " logged out...";
SendMessage(data); // send a logout message to the other chat peers
}
// debugging functions
static void errorHandler(Exception errorMsg)
{
MessageBox.Show(errorMsg.ToString()); // create a error-message-box
fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
}
static void fileWriter(string fileText, bool append)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
file.Close();
}
public static String GetTime(DateTime val)
{
return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
}
}
}
Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. See the example below:
IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);
IPAddress.Broadcast doesn't work in some network.
i need to recover all my message from my Outlook box. I use the OpenPop open source, but i can't recover the plain text (the value is null) and i don't understand why because when i check up my mail the plain text exist. When i try with the html version it works but i don't need this one in my project. Thanks to anyone who can help me.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using OpenPop.Mime;
using OpenPop.Pop3;
namespace EmailGmail
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string hostname = ***;
int port = **;
bool useSsl = true;
string username = ***;
string password = ***;
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(hostname, port, useSsl, username, password);
foreach (OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
}
}
public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using (Pop3Client client = new Pop3Client())
{
try
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
catch (Exception ex)
{
return null;
}
}
}
}
}
I had the same problem. I solved by going to pick the raw data of the body and using a method to convert its bytes to readable text (string).
string Body = msgList[0].MessagePart.MessageParts[0].GetBodyAsText();
Here is what you gets the body text.
msgList is the result of calling FetchAllMe messages, which gives you an array of messages. Every message has its MessagePart which contain the body text. Use GetBodyAsText to retrieve the body text. GetBodyAsText is already included in OpenPop library, so it's not a method of mine.
Hope this clears your doubts.
private void button7_Click(object sender, EventArgs e)
{
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(...);
StringBuilder builder = new StringBuilder();
foreach(OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
if(plainText != null)
{
// We found some plaintext!
builder.Append(plainText.GetBodyAsText());
} else
{
// Might include a part holding html instead
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
if(html != null)
{
// We found some html!
builder.Append(html.GetBodyAsText());
}
}
}
MessageBox.Show(builder.ToString());
}
I am working on a program for proof of concept that does a webrequest using WebClient.DownloadString("http://website/members/login.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);
to get the boolean value of wether or not the user is a valid login and then if it is it gives a success notification if it isn't ten it gives a fail notification.
The problem is when i press the button to try and login the first time it works fine but when i press it again the second tine the program freezes and gets stuck at the Webclient.download string.
If anyone can spot and tell me whats wrong that would be great. I am providing the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public static WebClient webclient = new WebClient();
HttpWebResponse wResp;
WebRequest wReq;
bool isConnected = false;
private String Session = "";
public Form1()
{
InitializeComponent();
}
public Boolean checkUser(String username, String password)
{
String login = `webclient.DownloadString("http://connorbp.info/members/auth.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);`
Boolean bLogin = Boolean.Parse(login);
if (bLogin)
{
Session = username + "-" + password;
}
return bLogin;
}
public int CanConnect(string dUrl)
{
wReq = WebRequest.Create(dUrl);
int cnt = Connect();
return cnt;
}
private int Connect()
{
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
isConnected = true;
return 1;
}
catch (Exception)
{
return 0;
}
}
private void button1_Click(object sender, EventArgs e)
{
int init = CanConnect("http://connorbp.info/members/auth.php");
if (init == 0)
{
notifyIcon1.ShowBalloonTip(200, "CBP Login", "Failed to connect to server! Try again later.", ToolTipIcon.Error);
}
else
{
if(checkUser(textBox1.Text, textBox2.Text))
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Logged In!", ToolTipIcon.Info);
}
else
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Invalid Username/Password!", ToolTipIcon.Error);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
notifyIcon1.ShowBalloonTip(20, "CBP Login", "for more cool things go to http://connorbp.info", ToolTipIcon.Info);
}
}
}
You are not closing the response.
The second call is trying to open something that is already open, therefore it hangs.
I want to send SMS using way2sms. I have tried following code
login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnconnect_Click(object sender, EventArgs e)
{
Session["id"] = txtmobileno.Text;
Session["pw"] = txtpw.Text;
Response.Redirect("/send.aspx");
}
}
}
send.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace WebApplication1
{
public partial class send : System.Web.UI.Page
{
string mbno, mseg, ckuser, ckpass;
private HttpWebRequest req;
private CookieContainer cookieCntr;
private string strNewValue;
public static string responseee;
private HttpWebResponse response;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null && Session["pw"] == null)
{
Server.Transfer("login.aspx");
}
connect();
try
{
lblError.Text = "";
lblError.Visible = false;
if (!(IsPostBack))
{
btnSend.Attributes.Add("onclick", "return Validate('" + txtTo.ClientID + "','" + txtMessage.ClientID + "');");
txtMessage.Attributes.Add("onchange", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
txtMessage.Attributes.Add("onkeyup", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
mbno = txtTo.Text;
mseg = txtMessage.Text;
sendSms(mbno, mseg);
txtTo.Text = "";
txtMessage.Text = "";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
public void connect()
{
ckuser = Session["id"].ToString();
ckpass = Session["pw"].ToString();
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com/auth.cl");
this.req.CookieContainer = new CookieContainer();
this.req.AllowAutoRedirect = false;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "username=" + ckuser + "&password=" + ckpass;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.cookieCntr = this.req.CookieContainer;
this.response.Close();
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//jsp/InstantSMS.jsp?val=0");
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "GET";
this.response = (HttpWebResponse)this.req.GetResponse();
responseee = new StreamReader(this.response.GetResponseStream()).ReadToEnd();
int index = Regex.Match(responseee, "custf").Index;
responseee = responseee.Substring(index, 0x12);
responseee = responseee.Replace("\"", "").Replace(">", "").Trim();
this.response.Close();
pnlsend.Visible = true;
lblErrormsg.Text = "connected";
}
catch (Exception ex)
{
lblErrormsg.Text = "Error connecting to the server...";
Session["error"] = "Error connecting to the server...";
lblError.Text = ex.ToString();
lblError.Text= ex.ToString();
//Server.Transfer("login.aspx");
}
}
public void sendSms(string mbno, string mseg)
{
if ((mbno != "") && (mseg != ""))
{
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//FirstServletsms?custid=");
this.req.AllowAutoRedirect = false;
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "custid=undefined&HiddenAction=instantsms&Action=" + responseee + "&login=&pass=&MobNo=" + this.mbno + "&textArea=" + this.mseg;
string msg = this.mseg;
string mbeno = this.mbno;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.response.Close();
lblErrormsg.Text = "Message Sent..... " + mbeno + ": " + msg;
}
catch (Exception)
{
lblErrormsg.Text = "Error Sending msg....check your connection...";
}
}
else
{
lblErrormsg.Text = "Mob no or msg missing";
}
}
protected void btnLogOut_Click(object sender, EventArgs e)
{
Session["id"] = null;
Session["pw"] = null;
Session["error"] = null;
Server.Transfer("login.aspx");
}
}
}
But it doesn't work. Is there any changes in this code that I have to do?
Please tell me any other way to send sms from desktop application or web application
I dont know way2sms but the easiest SMS API I have found is http://cp.bulksmsportal.co.za/sms_default.aspx
Code is really simple as well
public static void sendSMS(string Recepient, string Message)
{
//Recepient is the cellno in string format
StringBuilder sb = new StringBuilder();
sb.Append("http://www.mymobileapi.com/api5/http5.aspx?");
sb.Append("Type=sendparam");
sb.Append("&username={yourusername}");//add your username here
sb.Append("&password={yourpassword}");//add your password here
sb.AppendFormat("&numto={0}", Recepient);
string message = HttpUtility.UrlEncode(Message, ASCIIEncoding.ASCII);
sb.AppendFormat("&data1={0}", message);
try
{
////Create the request and send data to the SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(sb.ToString());
//Get response from the SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}
catch (Exception ex)
{
}
}
I used this : GSM Communication Library (GSMComm)
I am unable to upload large files to Sharepoint 2010. I am using Visual Studio 2010 and Language C#. I have tried multiple ways from content I have found online but nothing has worked. I have changed the settings and config files to the maximum allowed upload limits and still nothing. I am using the copy.asmx for small files which works fine and am trying UploadDataAsync when the file is too large and an exception is thrown but this is not working. Please take a look at the code below...
Any/all assistance is greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace ListsService
{
public class UploadDocumentcs
{
public string UploadResult { get; set; }
public string Errors { get; set; }
public UploadDataCompletedEventHandler WebClient_UploadDataCompleted { get; set; }
public byte[] content { get; set; }
public void UploadDocumentToSP(string localFile, string remoteFile)
{
string result = string.Empty;
SPCopyService.CopySoapClient client = new SPCopyService.CopySoapClient();
string sUser = "user";
string sPwd = "pwd";
string sDomain = "dmn";
System.Net.NetworkCredential NC = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential = NC;
try
{
client.Open();
string url = "http://SP/TestLibrary/";
string fileName = localFile.Substring(localFile.LastIndexOf('\\'), (localFile.Length - localFile.LastIndexOf('\\')));
fileName = fileName.Remove(0, 1);
string[] destinationUrl = { url + fileName };
System.IO.FileStream fileStream = new System.IO.FileStream(localFile, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
// Description Information Field
SPCopyService.FieldInformation descInfo = new SPCopyService.FieldInformation
{
DisplayName = "Description",
Type = SPCopyService.FieldType.File,
Value = "Test file for upload"
};
SPCopyService.FieldInformation[] fileInfoArray = { descInfo };
SPCopyService.CopyResult[] arrayOfResults;
uint result2 = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
// Check for Errors
foreach (SPCopyService.CopyResult copyResult in arrayOfResults)
{
string msg = "====================================" +
"SharePoint Error:" +
"\nUrl: " + copyResult.DestinationUrl +
"\nError Code: " + copyResult.ErrorCode +
"\nMessage: " + copyResult.ErrorMessage +
"====================================";
Errors = string.Format("{0};{1}", Errors, msg);
}
UploadResult = "File uploaded successfully";
}
catch (OutOfMemoryException)
{
System.Uri uri = new Uri("http://bis-dev-srv2:300/DNATestLibrary/");
(new System.Net.WebClient()).UploadDataCompleted += new UploadDataCompletedEventHandler(WebClient_UploadDataCompleted);
(new System.Net.WebClient()).UploadDataAsync(uri, content);
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
{
client.Abort();
UploadResult = "Upload aborted due to error";
}
if (client.State != System.ServiceModel.CommunicationState.Closed)
{
client.Close();
}
}
}
void WcUpload_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e != null)
{
UploadResult = "Upload Unuccessful";
}
else
{
UploadResult = "Upload Successful";
//throw new NotImplementedException();
}
}
}
}
Shaun
In order to get this to work, you will have to make changes to the SharePoint configuration to increase the upload limit and the time out. The link below shows the necessary steps to get large file uploads to work.
http://blogs.technet.com/b/sharepointcomic/archive/2010/02/14/sharepoint-large-file-upload-configuration.aspx
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.Net;
using System.IO;
namespace UploadTester
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnSelectFile_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadData(uri, "PUT", content);
MessageBox.Show("Upload Successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
byte[] GetByteArray()
{
FileStream fileStream = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
return content;
}
private void btnUploadAsync_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.UploadDataCompleted += new UploadDataCompletedEventHandler(webClient_UploadDataCompleted);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadDataAsync(uri, "PUT", content);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("Upload Successful");
}
else
{
MessageBox.Show(e.ToString());
}
}
}
}