Uploading and downloading small files to a cloud drive in-game? (Unity3D) - c#

I need any player's client to be able to upload and download files (they are text files that have replay data. I'm making a racing game and want players to be able to send and download replays.) while in-game. I'm trying to use Dropbox but I'm having problems. I'm open to other file hosting services but I don't really know how to send and get data from them. I keep making little changes here and there and they all give me different errors. Is there anything I'm doing blatantly wrong here? I'm expecting the main problem to be in the dropbox URL I'm using. Here's what my code looks like:
private void DownloadReplay()
{
string l_playerID = PlayFabManager.load_PlayfabId;
string l_levelID = PlayFabManager.load_levelID;
using (WebClient wc = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{l_playerID}{l_levelID}.replay");
string url = ("https://www.dropbox.com/s/f786vep0z9yd11s/"+ $"{l_playerID}{l_levelID}");
wc.Credentials = new NetworkCredential("xx", "xx");
wc.DownloadFile((new System.Uri(url)), path);
}
}
private void UploadReplay()
{
string s_playerID = PlayFabManager.load_PlayfabId;
string s_levelID = PlayFabManager.load_levelID;
using (WebClient client = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{s_playerID}{s_levelID}.replay");
string url = Path.Combine("https://www.dropbox.com/s/f786vep0z9yd11s/" + $"{s_playerID}{s_levelID}");
client.Credentials = new NetworkCredential("xx", "xx");
client.UploadFile(url, path);
}
}
Right now this one gives me an error 404, even though the file matching the string is in my dropbox.

Related

C# How to send a file to webhook and get sent file's link?

Hello im trying upload file to a link and i tried this:
`private void buttonInput_Click(object sender, EventArgs e)
{
try
{
using (WebClient client = new WebClient())
{
var resStr = client.UploadFile(#"https://anonfiles.com", #"C:\Users\sadettin\desktop\test.txt");
var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
var linkToFile = jObjResult["link"];
}
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
}`
But Im taking 404 error.
Now i want to send any txt file to my discord webhook address and take sent file's link.
How can i do?
Despite your claims, using the correct end-point and a non-zero bytes file does lead to an uploaded file:
using (WebClient client = new WebClient())
{
var resStr = client.UploadFile(#"https://api.anonfiles.com/upload", #"C:\tmp\test.txt");
var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
var linkToFile = jObjResult["data"]["file"]["url"]["full"].ToString();
MessageBox.Show(linkToFile);
}
Do note that the JSON structure that is returned is different then you seem to handle. The url is found in an attribute full under this path /data/file/url hence this line in my code example:
var linkToFile = jObjResult["data"]["file"]["url"]["full"];
Here is one of the full urls that the service returned to me with my test file
https://anonfiles.com/nai0Z3S0x5/test_txt
It is 106 bytes in total.

DevOps description field image download / Save file

Since we have moved to Dev Ops my application fails to download the images that are in any field stored in a work item.
I have an image URL that has already been stripped out of the description files via a regular expression.
If I take this link and paste it in to a browser then it returns the images (so the url is valid)
The issue is that within the call to download the image we dont have any authentication credentials and its trying to return me to a login page.
I do authenticate with the dev ops server within my application and it caches these.
readonly VssCredentials creds = new VssClientCredentials();
I have tried to use a webclient to make the call but you cant cast the VSScredentuals to system.net credentials
this used to work before
using (WebClient webClient = new WebClient())
{
byte[] data = webClient.DownloadData(src);
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
// If you want it as Png
yourImage.Save(#"c:\temp\path_to_your_file.png", ImageFormat.Png);
// If you want it as Jpeg
yourImage.Save(#"c:\temp\path_to_your_file.jpg", ImageFormat.Jpeg);
}
}
}
I have tried also using
using (var client = new TfvcHttpClient(new Uri(src), creds))
{
var itemRequestData = Create(src);
}
private static TfvcItemRequestData Create(string folderPath)
{
return new TfvcItemRequestData
{
IncludeContentMetadata = true,
IncludeLinks = true,
ItemDescriptors =
new[]
{
new TfvcItemDescriptor
{
Path = folderPath,
RecursionLevel = VersionControlRecursionType.Full
}
}
};
}
But how do i then write the itemRequestData to a file?
Or am i going about this the wrong way?
thanks
Try this:
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add("Authorization", "Basic " + base64Token);
byte[] data = webClient.DownloadData(src);
// ....
}
Where base64Token is your Personal Access Token converted to base64 with a ":" at the start.
For example if your token is abcdefg you need to convert :abcdefg to base64 and use it as the authorization token.

Text Encoding comes out corrupted after downloading from FTP

So i am making a program in c# with .net that uploads text files...
but everytime i upload a text file then download it on filezilla it comes out in chinese looking text..See here. im not sure if its because of encoding but if it helps heres my ftp code:
string ftpUsername = "#######";
string ftpPassword = "##########";
string localFilePath = path+ #"\" +FileName;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://###########/Logs/Text.txt", "STOR", localFilePath);
File.Delete(path + #"\" + FileName);
}
The reason the text file was coming out corrupted was not the upload method but the download method in FileZilla...
When you download you need to set the transfer type too binary...
this gets rid of the issue..

Extra data when uploading txt file to FTP server using C#

Ok, so I am testing uploading files to an FTP server by attempting to upload a text file with the contents of "HELLO WORLD".
I am given a return of"
"upload file completed System.Net.WebClient error -> cancelled ->False".
The file seems to appear on the server but when I open it, the contents read:
--------------8d30e4d69803578
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: application/octet-stream
HELLO WORLD
--------------8d30e4d69803578
the code I am using is:
string ftpUserName = "ftpUserName";
string ftpPassword = "ftpPassword";
string ftpURL = "ftp://ftpServer.com/text.txt";
string path = "pathToFile/test.txt"
public static void Test()
{
System.Uri uri = new System.Uri(ftpURL);
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
return;
}
using(WebClient wc = new WebClient())
{
wc.Credentials = new NetworkCredential(ftpUserName,ftpPassword);
wc.UploadFileCompleted += UploadFileCompleted;
wc.UploadFileAsync(uri,"STOR",path);
}
}
Any help would be appreciated
edit
I also just tried with a zip file and it is corrupt. Both the .txt and .zip are also far smaller once they reach the server, so I am assuming the upload has failed because of that error
edit 2
solved it using .net2.0's version of the FtpWebRequest
I have just verified - other than the async issue I mentioned, there's nothing wrong with your code.

Download a file from a Variable URL c#

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.

Categories