BackgroundDownloadAsync not downloading? - c#

I'm trying to use LiveConnectClient.BackgroundDownloadAsync to copy a file from Skydrive onto my computer. My code is below (this is a C# Metro app running on Win8).
var copy = connect.BackgroundDownloadAsync(f.id, dest);
LiveDownloadOperationResult result = await copy;
The result I get back contains no error, yet when I go have a look I see only the first 1K of my file. So my questions are:
Has someone used BackgroundDownloadAsync successfully?
Can someone suggest something I might have missed, that would match the symptoms?
Thanks!

The answer is to add "/content" to the ID of the file you want to download. Otherwise, you get the metadata.

Related

How do I overwrite a text file line by line using StreamWriter WriteLine in c#

As part of my c# learning, I have a simple game on a console application. I have now added a text file to record the top score. It has 4 lines, date, number of attempts, time in minutes and additional time in seconds. The text file is part of the project solution, and although I don't specify the full path, I can read the file with StreamReader and output the lines without any trouble. But if I have a new top score, and I wish to overwrite the values in the text file, nothing is happening. The text file remains unmodified.
I have tried using StreamWriter. It feels somewhat intuitive to use StreamReader ReadLine to bring the data into the application and StreamReader WriteLine to output. But the output piece is not working. For my sins, this is my code. There are some similar queries on stackooerflow, but I've not found a solution that appears to fit my query.
if (newBestScore== true)
{
DateTime dateToday = DateTime.Now;
string dateString=dateToday.ToShortDateString();
string currAttempts=CurrentAttempts.ToString();
using (StreamWriter newTopScore = new StreamWriter("TopScore.txt"))
{
newTopScore.WriteLine(dateString);
newTopScore.WriteLine(currAttempts);
newTopScore.WriteLine(timeTaken.Minutes);
newTopScore.WriteLine(timeTaken.Seconds);
newTopScore.Close();
}
}
I'll not fix your problem, but I'll tell you how you can fix all problems of this sort by yourself in the future.
Download Process Monitor and add a filter for your application, like so:
Process Name, contains, <myapp>.exe then Include and then add this filter by pressing the Add button.
Then start recording and look for TopScore.txt and see in which directory it looks for that file. You can use the find dialog for that (Ctrl+F):
Then have a look at the full file name of that file, so you know where it it being written. You can even right click and choose "Jump to ...".
Understand what a working directory is. The file will be written in the working directory if you didn't provide a full path.
Why go this way? This way proves that you have a problem independently. You don't change the source code. Whenever you change the source code and e.g. add diagnostics code like Console.WriteLine(Path.GetFullPath(...));, problems may disappear.

Libragnar(Libtorrent Wrapper) LocalTorrent File, Instead of URL? C#/C++

Question:
Does anyone know how to add a torrent to LibRagnar using a filepath to a torrent, instead of a Url? (LibRagnar is a libtorrent Wrapper)
libragnar = C#
libtorrent = C++
Alternatively if anyone knows How I can use Libtorrent To add the torrent to a session, But use a local file (Whilst still controlling Everything else using Libragnar).But I am not sure where to start with Libtorrent.
Reason For Problem:
I have to use a filepath because the Torrent Requires cookie login to access it. So I either Need to get Libragnar to use a CookieCollection when getting a torrent from a URL or make it use a local ".torrent" file.
Problem:
I am currently trying to use a filepath instead of URL and the Torrent Status gives an error:unsupported URL protocol: D:\Programming\bin\Debug\Tempfiles\File.torrent. Which wont allow me to start it.
Example:
var addParams = new AddTorrentParams
{
SavePath = "C:\\Downloads",
Url = "D:\\Programming\\bin\\Debug\\Tempfiles\\File.torrent"
};
Edit: Answer from Tom W (Posted in C# Chatroom)
var ati = new AddTorrentParams()
{
TorrentInfo = new TorrentInfo("C:\thing.torrent"),
SavePath = #"C:\save\"
};
Note About Answer: I attempted to edit Tom W's post and add the answer he gave me in the Chatroom, However I guess it got declined? But Since he was the one who helped me I wanted him to get credit, and also wanted anyone else having this issue, to have an answer. So I had to add the answer to the bottom of my question.
From the libtorrent documentation it appears that:
The only mandatory parameters are save_path which is the directory
where you want the files to be saved. You also need to specify either
the ti (the torrent file), the info_hash (the info hash of the
torrent) or the url (the URL to where to download the .torrent file
from)
Libragnar's AddTorrentParams appears to be a wrapper around add_torrent_params and has a property called TorrentInfo. I suspect if you avoid setting the URL, and set this property to an instance of TorrentInfo instead, you ought to get the result you want.
Disclaimer: I've never worked with torrents before, don't know this library, and don't work in C++.

Unable to open PDF programmatically

I'm struggling to open a PDF file inside of Unity. Currently, my application will open up the folder location instead of opening the actual PDF itself.
I've tried using both System.Diagnostics.Process.Startand Application.OpenURL but they all act the same.
Right now, my code looks like:
Application.OpenURL(Application.dataPath + "/PDFS/" + pdfFile);
Now when I hard code in the file location like below, it opens up the PDF correctly:
Application.OpenURL("C:\\Users\\user\\Documents\\Locator\\Assets\\PDFS\\foo.pdf");
Normally I'd leave it hard coded, but I need to allow one button to open any PDF. How can I resolve this?
The string output of the two lines below are most likely not equal.
Application.OpenURL(Application.dataPath + "/PDFS/" + pdfFile);
Application.OpenURL("C:\\Users\\user\\Documents\\Locator\\Assets\\PDFS\\foo.pdf");
Ensure the paths are the same and you should get the result you expect.
See the documentation for Application.OpenURL here:
http://docs.unity3d.com/ScriptReference/Application-dataPath.html
If you read to the bottom, you'll notice:
"Note that the string returned on a PC will use a forward slash as a folder separator."
This likely the reason why you're getting different results.
Also note that the value of Application.OpenURL changes based on the platform.
string pdfURL = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "Documents/keyboard-shortcuts-Visual-Studio-Code.pdf";
it return below url and run in browser
http://localhost:1727/Documents/keyboard-shortcuts-Visual-Studio-Code.pdf
thanks
upendra

How to play sound from cocos2d-xna personal folder

How can I play a sound from the
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal
folder?
I have tried:
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Sounds/Twing.mp3");
CCSimpleAudioEngine.SharedEngine.PlayEffect(path);
But it doesn't work
you get an exception ?
i assume that the specified sound is loaded via the content pipleline,
so you would need to add that to your content project.
So if you see ContentPipeline, ContentLoader or something in the stack trace, this may be the correct answer.
I dit not find a way to directly pass the audio.
With images that is possible.

How to check if file exists in a Windows Store App?

Is there any other way of checking whether a file exists in a Windows Store app?
try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.xml");
//no exception means file exists
}
catch (FileNotFoundException ex)
{
//find out through exception
}
According to the accepted answer in this post, there is no other way at the moment. However, the File IO team is considering changing the the api so that it returns null instead of throwing an exception.
Quote from the linked post:
Currently the only way to check if a file exists is to catch the
FileNotFoundException. As has been pointed out having an explicit
check and the opening is a race condition and as such I don't expect
there to be any file exists API's added. I believe the File IO team
(I'm not on that team so I don't know for sure but this is what I've
heard) is considering having this API return null instead of throwing
if the file doesn't exist.
This may be old, but it looks like they've changed how they want you to approach this.
You're supposed to attempt to make the file, then back down if the file already exists. Here is the documentation on it. I'm updating this because this was the first result on my Google search for this problem.
So, in my case I want to open a file, or create it if it doesn't exist. What I do is create a file, and open it if it already exists. Like so:
save = await dir.CreateFileAsync(myFile, CreationCollisionOption.OpenIfExists);
I stumbled on to this blog post by Shashank Yerramilli which provides a much better answer.
I have tested this for windows phone 8 and it works. Haven't tested it on windows store though
I am copying the answer here
For windows RT app:
public async Task<bool> isFilePresent(string fileName)
{
var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
return item != null;
}
For Windows Phone 8
public bool IsFilePresent(string fileName)
{
return System.IO.File.Exists(string.Format(#"{0}\{1}", ApplicationData.Current.LocalFolder.Path, fileName);
}
Check if a file exists in Windows Phone 8 and WinRT without exception
You can use the old Win32 call like this to test if directory exist or not:
GetFileAttributesExW(path, GetFileExInfoStandard, &info);
return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? false: true;
It works in Desktop and Metro apps:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946%28v=vs.85%29.aspx
Microsoft has added a new function to StorageFile in Windows 8.1 to allow user engineers to determine if a file can be accessed: IsAvailable
The other means to check is by getting files in local folder
var collection = ApplicationData.Current.LocalFolder.GetFilesAsync()
Using this method and then iterating over all the elements in the collection and check for its availability.
I tried to write my own using old tricks:
GetFileAttributesEx() always seems to end up with ERROR_ACCESS_DENIED if file selected via FileOpenPicker;
Ditto for FindFirstFileEx();
_stat() always ends up with ENOENT when file selected via FileOpenPicker;
CreateFile2() with CREATE_NEW option works -- if file does exist it will fail with INVALID_HANDLE_VALUE return value and ERROR_FILE_EXISTS last error; if file does not exist you have to remember to delete created file afterwards.
All in all -- you're better of sticking with exception handling method.
8.1 got something like this, I tried it worked.
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.TryGetItemAsync("mytext.txt") as IStorageFile;
if (file == null)
{
//do what you want
}
else
{
//do what you want
}
http://marcominerva.wordpress.com/2013/11/19/how-to-check-if-a-file-exists-in-a-windows-8-1-store-apps-no-more-exception-handling/
Dim myPath As StorageFolder
If (From i In Await KnownFolders.MusicLibrary.GetFoldersAsync() Where i.Name = "PodBong").Count = 1 Then
myPath = Await KnownFolders.MusicLibrary.GetFolderAsync("PodBong")
Else
myPath = Await KnownFolders.MusicLibrary.CreateFolderAsync("PodBong")
End If
The documentation for TryGetItemAsync says, "This example shows how to checkfor the existence of a file." It seems that this API is officially intended to serve that purpose.

Categories

Resources