Im working on a Discord bot and want to create this:
I have a string that reads the content of a local file, but I want to upload that file to a specific website (for example GitHub) and use it, instead of the local file (basically, I want to get rid of the local file and be able to use the uploaded file).
I have this simple line of code:
string[] contentFile = File.ReadAllLines("files/file.txt");
Can somebody help me out here?
Edit: The file contains the lines "1", "2", "3" (and so on), and I want to put these lines in a string array so that I can get access to "1" with contentFile[0], to "2" with contentFile[1] and so on and so forth. It works perfect with a local file, but I do not know how to get access to the uploaded file and the lines within.
So this is how I got it to work (if anyone is interested):
using (var client = new WebClient())
{
client.DownloadFile("www.website.com/file.txt", "files/file.txt");
}
string[] fileContent = File.ReadAllLines("files/file.txt");
while (true)
{
try
{
if (File.Exists("files/file.txt")) File.Delete("files/file.txt");
break;
}
catch (IOException)
{
codeTrue = true;
}
}
This basically downloads the file, reads it and deletes it afterwards. The only "problem" is that everytime I update the file on the website, I need to restart the application, else the string array wont be updated. You can solve that problem by adjusting the code a bit and creating an update-loop.
Related
I have a program that checks a directory of zip files which get uploaded (via FTP) to my server daily (from different clients), each zip needs to contain a series of particular data files, so I am using the ZipArchive class to open the file, check the contents and make sure it contains the files we need and also make sure they have been recently updated (to make sure we're not uploading an old copy)
My program works for the most part, the problem I am facing is that if a file is currently being uploaded while Im trying to check it, my checker program is freezing. I cant seem to find any way around it.
Here is what Ive tried:
using (var zip = ZipFile.OpenRead("FileName")) // <--This is where it freezes.
{
// Check the contents
}
and I tried this:
using (var fs = File.OpenRead("FileName"))
{
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) // <-- This is where it freezes.
{
// Check the contents
}
}
Ultimately I would just like it to throw an exception so I can continue onto the next file.
If anyone has had a similar issue or have any suggestions on what I can try it would be appreciated.
I am trying to upload files to S3 after a user uploads a file to my API. I obviously don't want them to live on MY server, in fact I'd prefer they never exist on the server at all. My problem is that the files appear to remain in use for the lifetime of server app! Here is the code:
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var provider = GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
var originalFileName = GetDeserializedFileName(result.FileData.First());
var fi = new FileInfo(result.FileData.First().LocalFileName);
var extension = Path.GetExtension(originalFileName).ToLower();
var amazonKey = S3Helper.Upload(fi.FullName, extension);
// DELETE THE FILE HERE (BodyPart_2f33be26-09a2-4ae3-8b89-4158b99fe32d)
File.Delete(fi.FullName); // This doesn't work, file in use error...
return this.Request.CreateResponse(HttpStatusCode.OK, new Img{
Extension = extension,
S3Key = amazonKey.Key,
OriginalFilename = originalFileName
});
}
How, when or where do I delete these files? OR is there a way to keep the files from being written to my server's disk in the first place?
The similar question shows that this approach should work in general. The only visible differences are:
You're using FileInfo. So why don't you use FileInfo's Delete method?
You're using S3Helper.Upload(fi.FullName, extension). Try to comment this line out to determine if it locks the file.
Not sure but s3helper.upload might be uploading on background thread. Try this
While(true){
try {
// delete file
break;
} catch () {
Thread.Sleep(1000);
}
}
Just looked at s3 docs and yes it uses not just a background thread but multiple!
Uploads the specified file. The object key is derived from the file's name. Multiple threads are used to read the file and perform multiple uploads in parallel. For large uploads, the file will be divided and uploaded in parts using Amazon S3's multipart API. The parts will be reassembled as one object in Amazon S3.
I am looking to download my files in public folder from One Drive, but it doesn't download the files.
Here is the scenario:
In public folder I have another folder with multiple files in it and is accessible widely.
for test purpose I have shared all the files in public folder (I don't if it's proper way of sharing it).
The following links are provided for me to download the file:
From shared folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69!646&authkey=!AGRCGuw8Y2_p9mA&ithint=folder%2c.mp3
From public folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69%21646
Direct link http://1drv.ms/1z9XlW6 -
I am using BackgroundTransferRequest to download the file using below code:
string filePathToDownload = string.Empty, fileName = "111.mp3";
filePathToDownload = "http://1drv.ms/1z9XlW6";
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
The file is 300Kb, but this only downloads 6 Kb.
How can I directly download the file from the links above (any of them)?
thanks!
If you replace the word redir with download in the url you get the raw file instead of the webpage i.e.
https://onedrive.live.com/download?resid=DBBC281099F4FE69%21646
Basically, you can't. Those links are links to the web content that shows the files you have shared. If your scenario doesn't mind asking the user to log in to OneDrive, then you can use the Live SDK to access these files.
To access your public folder from Live SDK, you need to either use Live SDK to get the folder-id for your public folder, or convert the IDs in the URL you copied into the format the Live SDK uses:
folder.<user-id>.<folder-resid>
Where is the part of before the !. In general you shouldn't construct an ID, since it's possible the IDs will change in the future, and instead you should retrieve the ID from the service. However, with the URL you pasted the ID would be:
folder.DBBC281099F4FE69.DBBC281099F4FE69!646
Which will allow you to call
https://apis.live.net:443/v5.0/folder.DBBC281099F4FE69.DBBC281099F4FE69!646/files?access_token=<valid_token>
and retrieve the IDs for the individual files, which you can then download via Live SDK following these details: http://msdn.microsoft.com/en-US/library/dn659726.aspx#download_a_file
For those who are still looking for a response to that question.
The easiest way to find the file path is to go to One Drive on the web and right-click on the file that we want and select Embed. Ξ€hen on the right we see the info window to integrate our file into a page. Inside the iframe is the source of the file. Then we have to replace the word embed with the word download and that's it.
Try something like this
//we first need the file id
string id = string.Empty;
//we need to get all of the filenames stored in the root of the skydrive account
LiveOperationResult result = await this.client.GetAsync("me/skydrive/files");
//lets make a list of all these filenames
List<object> items = result.Result["data"] as List<object>;
//for every filename, check if it is what we want, in this case "sample.txt"
//if it is what we want, get the id and save it to out already defined id value
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == "sample.txt")
{
id = file["id"].ToString();
}
}
//to download the file we need to use the id + "/content"
LiveDownloadOperationResult result2 = await client.DownloadAsync(string.Format("{0}/content", id));
//once the file had downloaded, lets copy it to IsolatedStorage
Stream stream = result2.Stream;
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileToSave = storage.OpenFile("sample.txt", FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(fileToSave);
stream.Flush();
stream.Close();
}
}
here client is the object of LiveConnectClient class.
Import
using Microsoft.Live;
using Microsoft.Live.Controls;
Here is use txt file as an example. Go through this example:http://www.baileystein.com/2013/10/20/skydrive-how-to-upload-and-download-a-text-file-on-wp8/
I have a project where I get a list of file location strings that I want to save locally. I want to use a FileUploader to do so. I am trying something like this so far:
FileUpload filesaver = new FileUpload();
//Iterate over each files (InputFiles is a linked list of file locations)
foreach (string File in InputFiles)
{
//Get file
Stream fileLoaded = OpenFile(File);
filesaver.FileContent = fileLoaded;
//Save file
filesaver.SaveAs(DownloadLocation);
//Code...}
The problem is that filesaver.FileContent = fileLoaded; is not a valid call (FileContent is read only).
How would I be able to get the file to the file loader so that I can save it if I have a string of that file location?
Edit I am using the FileUpload Class
The ASP.NET FileUploader has the client side send the file to the server side. It does not send a file path as a string, so there is no way to intercept the file path and "upload" on the server side. if that is your intent, you are not going to find a way to get there from here.
If you want to save the actual file binary bits once it gets to the server, there are plenty of examples out there that persist the data to databases or file system.
If you are trying to get paths as strings, the file uploader is not your best choice, but note that the file path strings, if they are local to the client, are of no use on the server side.
You can just use:
If (filesaver.HasFile)
{
filesaver.SaveAs("C:\YourFilePath\" & filesaver.FileName);
}
I have the following code where i save the xml file into this particular location shown below
public bool GetList(string keyword1, string streetname, string lat, string lng, string radius)
{
XmlDocument xmlDoc= CreateXML( keyword1,streetname,lat,lng,radius);
xmlDoc.Save(#"C:\Documents and Settings\Vijay.EKO-03\Desktop\blockseek3-9-2010\Block3.xml");
return true;
}
This Block3.xml file gets stored in my application folder, i refer to that particular Block3.xml using this code
function searchLocationsNear()
{
var searchUrl = "Block3.xml";
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
I am able to parse that Block3.xml and display results but my problem is during second iteration again when i try to save Block3.xml
xmlDoc.Save(#"C:\Documents and Settings\Desktop\blockseek3-9-2010\Block3.xml");
The previous Block3.xml file gets replaced by new one and gets stored in application folder
when i execute var searchUrl="Block3.xml"; it reads the first Block3.xml not the replaced one ,can any one help to tackle this code .
Is their any syntax to clear the saved xmldoc file in that particular folder .
Most likely, the GXml class retains an open file handle. Check the documentation: if it implements IDisposable, wrap your processing code like this:
using ( var xml = GXml.parse(data) )
{
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
}
This also assumes that the parse() method is the one that actually loads and reads the file. If you don't release the file handle, your process doesn't know that there's another version in the file system. (And other nasty stuff can happen, depending on the exact mode the O/S opened the file in.)
I trust your production code won't contain these hard coded paths...?