I am trying to copy a file which is on a server and all I've got is it's URI format path.
I've been trying to implement copying in C# .NET 4.5, but seems like CopyFile is not good with handling URI formats.
So I've used IronPython with shutil, but seems like it is also not good with URI format paths.
How do I get that file local?
private string CopyFile(string from, string to, string pythonLibDir, string date)
{
var dateTime = DateTime.Today;
if (dateTime.ToString("yy-MM-dd") == date)
{
return "";
}
var pyEngine = Python.CreateEngine();
var paths = pyEngine.GetSearchPaths();
paths.Add(pythonLibDir);
pyEngine.SetSearchPaths(paths);
pyEngine.Execute("import shutil\n" +
"shutil.copyfile('" + from + "', '" + to + "')");
return dateTime.ToString("yy-MM-dd");
}
I take all paths from xml config file.
you can use a webclient and then get the file on a particular folder.
using (WebClient wc = new WebClient())
wc.DownloadFile("http://sitec.com/web/myfile.jpg", #"c:\images\xyz.jpg");
or you can also use: HttpWebRequest inc ase you just want to read the content from a file from a server.
var http = (HttpWebRequest)WebRequest.Create("http://sitetocheck.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With Python
import urllib
urllib.urlretrieve("http://www.myserver.com/myfile", "myfile.txt")
urlretrieve
Copy a network object denoted by a URL to a local file, if necessary. If the URL points to a local file, or a valid cached copy of the object exists, the object is not copied.
Related
I have written a console app in c# following this tutorial: https://learn.microsoft.com/en-gb/training/modules/msgraph-access-file-data/3-exercise-access-files-onedrive
Now when I download a file from my OneDrive via the console app using Microsoft Graph API, all the files get downloaded in type "File". However, the files are of type "Docx".
So how do I ensure that the files get downloaded in their original extension format? (.docx, .ppt, .csv, etc.)
var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
var request = client.Me.Drive.Items[fileId].Content.Request();
var stream = request.GetAsync().Result;
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "driveItem_" + fileId + ".file");
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);
Make a request to get file and read name property which represents the name of the item (filename and extension).
var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
// make a request to get the file
var file = client.Me.Drive.Items[fileId].Request().GetAsync().Result;
var fileName = file.Name;
var request = client.Me.Drive.Items[fileId].Content.Request();
var stream = request.GetAsync().Result;
// create a file with the same name
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);
I have a pdf file on my local machine and I want to compare it with my http response which is in pdf format. I am new to this and I have no idea how to do it. Can someone please suggest how can I do it. Please find below my code:
/******Get the document********/
String urlDoc = "https://abcd/v1/requests/"+order.request.id+"/"+"document";
HttpWebRequest requestDoc = (HttpWebRequest)WebRequest.Create(urlDoc);
requestDoc.Headers.Add("authorization", id_token);
requestDoc.Method = "GET";
var webResponse4 = requestDoc.GetResponse();
var webStream4 = webResponse4.GetResponseStream();
var responseReader4 = new StreamReader(webStream4);
var response4 = responseReader4.ReadToEnd();
Report.Success("Response : " + response4.ToString());
Request reqs = JsonConvert.DeserializeObject<Request>(response4);
// Clean up the streams.
responseReader4.Close();
Output of this is in pdf format.
Compare the files using file hashes
Use the MD5 file hashing method to hash files.
Use the code here
I am working on c# .Net 4.5
I have to upload some files on MongoDB and in other module, I have to get them back based on metadata.
for that I am doing like below,
static void uploadFileToMongoDB(GridFSBucket gridFsBucket)
{
if (Directory.Exists(_sourceFilePath))
{
if (!Directory.Exists(_uploadedFilePath))
Directory.CreateDirectory(_uploadedFilePath);
FileInfo[] sourceFileInfo = new DirectoryInfo(_sourceFilePath).GetFiles();
foreach (FileInfo fileInfo in sourceFileInfo)
{
string filePath = fileInfo.FullName;
string remoteFileName = fileInfo.Name;
string extension = Path.GetExtension(filePath);
double fileCreationDate = fileInfo.CreationTime.ToOADate();
GridFSUploadOptions gridUploadOption = new GridFSUploadOptions
{
Metadata = new BsonDocument
{{ "creationDate", fileCreationDate },
{ "extension", extension }}
};
using (Stream fileStream = File.OpenRead(filePath))
gridFsBucket.UploadFromStream(remoteFileName, fileStream, gridUploadOption);
}
}
}
and downloading,
static void getFileInfoFromMongoDB(GridFSBucket bucket, DateTime startDate, DateTime endDate)
{
double startDateDoube = startDate.ToOADate();
double endDateDouble = endDate.ToOADate();
var filter = Builders<GridFSFileInfo>.Filter.And(
Builders<GridFSFileInfo>.Filter.Gt(x => x.Metadata["creationDate"], startDateDoube),
Builders<GridFSFileInfo>.Filter.Lt(x => x.Metadata["creationDate"], endDateDouble));
IAsyncCursor<GridFSFileInfo> fileInfoList = bucket.Find(filter); //****
if (!Directory.Exists(_destFilePath))
Directory.CreateDirectory(_destFilePath);
foreach (GridFSFileInfo fileInfo in fileInfoList.ToList())
{
string destFile = _destFilePath + "\\" + fileInfo.Filename;
var fileContent = bucket.DownloadAsBytes(fileInfo.Id); //****
File.WriteAllBytes(destFile, fileContent);
}
}
in this code (working but) I have two problems which I am not sure how to fix.
If i have uploaded a file and I upload it again, it actually gets
uploaded. How to prevent it?
Ofcourse both uploaded files have different ObjectId but while uploading a file I will not be knowing that which files are already uploaded. So I want a mechanism which throws an exception if i upload already uploaded file. Is it possible? (I can use combination of filename, created date, etc)
If you have noticed in code, actually i am requesting to database server twice to get one file written on disk, How to do it in one shot?
Note lines of code which I have marked with "//****" comment. First I am querying into database to get fileInfo (GridFSFileInfo). I was expecting that I could get actual content of file from this objects only. But I didnot find any related property or method in that object. so I had to do var fileContent = bucket.DownloadAsBytes(fileInfo.Id); to get content. M I missing something basic here ?
Currently our application is working with a Word Document which is stored locally in the file system. It reads it and manipulate it, returning the updated document to the user. I have the following code:
var tempFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".docx");
File.Copy(fileName, tempFileName);
if (!File.Exists(tempFileName))
throw new ArgumentException("Unable to create file: " + tempFileName);
using (var doc = WordprocessingDocument.Open(tempFileName, true))
it was creating a temp file and copying the word doc and then manipulating the temp file. This way the original word doc is untouched.
We were recently asked to move the word doc into sharepoint, i'm able to connect using the WebClient class and verify the file exists, but I'm not able to figure out how to copy the file from Sharepoint. I've tried:
var client = new WebClient { Credentials = CredentialCache.DefaultCredentials };
// Create a request for the URL.
WebRequest request = WebRequest.Create(fileName);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
var response = (HttpWebResponse)request.GetResponse();
//check response status
if (String.Compare(response.StatusDescription, "OK", StringComparison.OrdinalIgnoreCase) == 0)
{
client.DownloadFile(fileName, Guid.NewGuid() + ".docx");
//URL exists so that means file exists
return true;
}
throw new ArgumentException("File \"" + fileName + "\" do not exists");
Problem is when I call DownloadFile it works, but I don't know where that file is sent. Is there a way to connect to the file in sharepoint and just copy it over to the users tempath as the original way?
We have been requested to go and Download an order file from our customers site via a url.
I want to do something like this.
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
But the URL will be variable as we have to specify the Date and Time within the URL we post.
And the File we download will be variable also.
As I'm new to C# I would like some advise as to how to achieve this?
Thanks In Advance
It depends on how the URLs will be generated. Do they follow a pattern? Do you know them in advance?
private void GetVariableFile(string remoteUri, string filename) {
string myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient()) {
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
//Do stuffs
}
}
You might wanna pass the Uri & the file obtained to a method which will handle the download and the elaboration, or in case you need to return the result, change the return type so that it can return the info you need.