i'm new here,
help me out here please,
i am working with web service and doing upload file.
here's my code for uploading file
private void Button_Click(object sender, RoutedEventArgs e)
{
testServiceClient = new TestServiceClient();
var uploadFile = "C:\\Computer1\\Sample.csv";
try
{
var dir = #"\\Computer2\UploadedFile\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadFile);
var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
client.Dispose();
MessageBox.Show("ok");
testServiceClient.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
i can upload file in the same network, but my question is this,
how can i upload file when the two computer is not in the same network?
i've tried changing the
var dir = #"\\Computer2\UploadedFile\";
to
var dir = #"https://Computer2/UploadedFile/";
but i'm getting an error 'unable to connect to remote server'
help me out here pls.
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://Computer2/UploadedFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadedFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.
This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service
Related
I want to show the progress of a downloading process on my ProgressBar. I tried to do somethings like this code for upload, but I failed. Here is an example of my failed attempts
private void button5_Click(object sender, EventArgs e)
{
Task.Run(() => Download());
}
private void Download()
{
try
{
int Port = (int)numericUpDown1.Value;
string Host = comboBox1.Text;
string Username = textBox3.Text;
string Password = textBox4.Text;
string SourcePath = textBox5.Text;
string RemotePath = textBox6.Text;
string FileName = textBox7.Text;
using (var file = File.OpenWrite(SourcePath + FileName))
using (var Stream = new FileStream(SourcePath + FileName, FileMode.Open))
using (var Client = new SftpClient(Host, Port, Username, Password))
{
Client.Connect();
progressBar1.Invoke((MethodInvoker)
delegate
{
progressBar1.Maximum = (int)Stream.Length;
});
Client.DownloadFile(RemotePath + FileName, /*file*/ Stream, DownloadProgresBar);
Client.Disconnect();
}
}
catch (Exception Ex)
{
System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DownloadProgresBar(ulong Downloaded)
{
progressBar1.Invoke((MethodInvoker)
delegate
{
progressBar1.Value = (int)Downloaded;
});
}
Thank you in advance
As you correctly did, similarly to the code for displaying progress of file upload, you have to provide a callback to the downloadCallback argument of SftpClient.DownloadFile.
public void DownloadFile(
string path, Stream output, Action<ulong> downloadCallback = null)
Also you correctly download on a background thread. Alternatively, you could use an asynchronous upload (SftpClient.BeginDownloadFile).
What is wrong and needs change:
You have to open/create the local file for writing (FileMode.Create).
You have to retrieve a size of the remote file, not the local one (not existing yet). Use SftpClient.GetAttributes.
Example using a background thread (task):
private void button1_Click(object sender, EventArgs e)
{
// Run Download on background thread
Task.Run(() => Download());
}
private void Download()
{
try
{
int Port = 22;
string Host = "example.com";
string Username = "username";
string Password = "password";
string RemotePath = "/remote/path/";
string SourcePath = #"C:\local\path\";
string FileName = "download.txt";
string SourceFilePath = SourcePath + FileName;
using (var stream = new FileStream(SourceFilePath, FileMode.Create))
using (var client = new SftpClient(Host, Port, Username, Password))
{
client.Connect();
string RemoteFilePath = RemotePath + FileName;
SftpFileAttributes attrs = client.GetAttributes(RemoteFilePath);
// Set progress bar maximum on foreground thread
int max = (int)attrs.Size;
progressBar1.Invoke(
(MethodInvoker)delegate { progressBar1.Maximum = max; });
// Download with progress callback
client.DownloadFile(RemoteFilePath, stream, DownloadProgresBar);
MessageBox.Show("Download complete");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void DownloadProgresBar(ulong uploaded)
{
// Update progress bar on foreground thread
progressBar1.Invoke(
(MethodInvoker)delegate { progressBar1.Value = (int)uploaded; });
}
For upload see:
Displaying progress of file upload in a ProgressBar with SSH.NET
I want to create a C# application using windows forms that let me upload files to a webserver, i have seen a lot of tutorial and everyone of them prove to be useless to solve my problem.
and with my project i have the next code in the button for upload
WebClient client = new WebClient();
client.UploadFile("http://localhost:8080/", location);
from here i had have several errors, an try multiple ideas, some of my more common errors are 404 not found or innaccessible path, also sometimes it doenst display me an error and works but the file doesn't save in the indicated path.
some of the links i use to solve the problem are the next ones:
http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx
http://www.c-sharpcorner.com/Blogs/8180/
How to upload a file in window forms?
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(#"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("http://www.yoursite.com/UploadMethod/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadMethod()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
winform
string fullUploadFilePath = #"C:\Users\cc\Desktop\files\test.txt";
string uploadWebUrl = "http://localhost:8080/upload.aspx";
client.UploadFile(uploadWebUrl , fullUploadFilePath );
asp.net create upload.aspx as below
<%# Import Namespace="System"%>
<%# Import Namespace="System.IO"%>
<%# Import Namespace="System.Net"%>
<%# Import NameSpace="System.Web"%>
<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
}
}
</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
you should set in win app
WebClient myWebClient = new WebClient();
string fileName = "File Address";
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);
then set read and write permission for SubDir
create a simple API Controller file in the Controllers folder and name it UploadController.
Let’s modify that file by adding a new action that will be responsible for the upload logic:
[HttpPost, DisableRequestSizeLimit]
public IActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _host.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
string ext = Path.GetExtension(file.FileName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = "";
string name = Path.GetFileNameWithoutExtension(file.FileName);
string fullPath = Path.Combine(newPath, name + ext);
int counter = 2;
while (System.IO.File.Exists(fullPath))
{
fileName = name + "(" + counter + ")" + ext;
fullPath = Path.Combine(newPath, fileName);
counter++;
}
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok();
}
return Ok();
}
catch (System.Exception ex)
{
return BadRequest();
}
}
We are using a POST action for the upload-related logic and disabling the request size limit as well.
and use code below in Winform
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://localhost/api/upload");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
client.UploadFileAsync(uri, directoryfile);
client.UploadFileCompleted += Client_UploadFileCompleted;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show("done");
}
Goodluck
Hi Im trying to display the Items I saved in a gridfs in a datagrid view and retrieve them by clicking it, but So far Im having trouble just querying mongo. Im not sure what the nominal Document type it requires
var cursor = collection.FindAs()
most other examples use collection.Find(). But I didnt tie Mongo to a class.
heres my code , can you help me get it to work.
public partial class WebForm1 : System.Web.UI.Page
{
MongoClient client;
MongoServer server;
MongoDatabase database;
MongoGridFs gridFs;
MongoCollection gridCol;
protected void Page_Load(object sender, EventArgs e)
{
client = new MongoClient();
server = client.GetServer();
database = server.GetDatabase("mydb");
gridCol = database.GetCollection("fs");
}
protected void Button1_Click1(object sender, EventArgs e)
{
//gridCol.FindAllAs<CFilez>
MongoCollection collection = database.GetCollection("fs");
var searchQuery = Query.EQ("gefunden", "one");
var cursor = collection.FindAs(
MongoCursor<CFilez> cursor = collection.FindAllAs<CFilez>();
cursor.SetLimit(5);
var list = cursor.ToList();
GridView1.DataSource = list;
GridView1.DataBind();
StatusLabel.Text = "Jive";
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
client = new MongoClient();
server = client.GetServer();
database = server.GetDatabase("mydb");
string filename = FileUpload1.FileName;
////File file = File.OpenRead(filename);
FileUpload1.SaveAs(Server.MapPath("~/Data/") + filename);
String Fpath = Server.MapPath("~/Data/") + filename;
////FileUpload1.SaveAs(Server.MapPath("~/Data/") + filename);
////var id = ObjectId.Empty;
//Stream file = File.OpenRead(Fpath);
////gridFs.AddFile(file, filename);
//gridFs.AddFile(filename);
using (var fs = new FileStream(Fpath, FileMode.Open))
{
var gridFsInfo = database.GridFS.Upload(fs, filename);
var fileId = gridFsInfo.Id;
}
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
*Hi all,
I've tried file upload to .net server using c#.
Im just using the c:/inetpub/wwwroot as the server location.
My java code is,
public class MainActivity extends Activity {
InputStream inputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.two);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,90, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1/AndroidUpload/uploadImage.cs");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
String the_response_string = convertResponseToString(response);
Toast.makeText(this, "Response"+the_response_string, Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this,"Error1", Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
//TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this,"Error2", Toast.LENGTH_SHORT).show();}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this,"Error3", Toast.LENGTH_SHORT).show();
}
}
public String convertResponseToString(HttpResponse response)throws IllegalStateException,IOException {
// TODO Auto-generated method stub
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength();
Toast.makeText(this, "ContentLength"+contentLength, Toast.LENGTH_SHORT).show();
if(contentLength<0){
}
else{
byte[] data = new byte[512];
int len = 0;
try {
while(-1 != (len=inputStream.read(data))){
buffer.append(new String(data,0,len));
}
inputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res = buffer.toString();
Toast.makeText(this, "Result"+res, Toast.LENGTH_SHORT).show();
}
return res;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And my c# code for uploading is,
protected void Page_Init(object sender, EventArgs e)
{
string vTitle = "";
string vDesc = "";
string FilePath = Server.MapPath("/files/two.png");
if (!string.IsNullOrEmpty(Request.Form["title"]))
{
vTitle = Request.Form["title"];
}
if (!string.IsNullOrEmpty(Request.Form["description"]))
{
vDesc = Request.Form["description"];
}
HttpFileCollection MyFileCollection = Request.Files;
if (MyFileCollection.Count > 0)
{
// Save the File
MyFileCollection[0].SaveAs(FilePath);
}
}
When Run, it throws IOException. And the file is not uploaded into that folder. Tried php code too with same result.
Where is the problem?
To connect from your emulator to your PC web-server, you need to follow the addressing convention currently used by Android. To be more specific, 10.0.2.2 is the address you want to use.
Also make sure that your AndroidManifest.xml contains the permission for Internet usage. Cheers
This is a common problem. In fact you should host your asp.net web app in an iis web server (at your computer) and get your computer ip address (by ipconfig command in cmd), then put your ip address instead of "http://127.0.0.1/AndroidUpload/...". It could be like "http://192.168.1.2/AndroidUpload/..."
Android emulator cant understand 127.0.0.1 (localaddress)
Edited:
I dont how to upoad files with asp.net web forms, but If I were you I would write a simple asp.net mvc application and in a controller, I declare a action like this:
[HttpPost]
public ActionResult UploadItem()
{
var httpPostedFileBase = Request.Files[0];
if (httpPostedFileBase != null && httpPostedFileBase.ContentLength != 0)
{
//save file in server and return a string
return Content("Ok");
}
else
{
return Content("Failed")
}
}
i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}
Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}
i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete
/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}