How can I move a downloaded file to the users temp path? - c#

I've looked it up on google, tried any answers for myself and none worked. I want to download 2 files and save them both to the users temp file (C:\Users%UserName%\AppData\Local\Temp). I can easily find the temp file using a string (string tempPath = Environment.GetEnvironmentVariable("TEMP");) I just can't get farther than that at this time.

You can download directly into the temp folder:
using System.Net;
string tempPath = Environment.GetEnvironmentVariable("TEMP");
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/file1.txt", #$"{tempPath}\file.txt");
client.DownloadFile("http://example.com/file/file2.txt", #$"{tempPath}\file2.txt");
}
Or move the already downloaded file:
using System.IO;
string tempPath = Environment.GetEnvironmentVariable("TEMP");
File.Move(#"C:\User\Downloads\Filename.txt", #$"{tempPath}\file.txt");
File.Move(#"C:\User\Downloads\Filename2.txt", #$"{tempPath}\file2.txt");
The # before the string is the string literal and The $ is the string interpolation you can search for these nice features later.

Adding to the accepted answer:
you can also derive the download-folder path to work on machine which use a different download folder as the default. You can find input on that here: How to programmatically derive Windows Downloads folder "%USERPROFILE%/Downloads"?
So if you chose to implement the second solution (moving files already downloaded) and need to roll this out on other machines than your own, this probably is a good idea.

Related

Getting the contents of a file in Visual Studio without opening the file from an extension

I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):
textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text = editPoint.GetText(textDocument.EndPoint);
I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).
I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?
You can get the path from a ProjectItem by reading its properties.
var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()
After you have the path you can read its content with System.IO.
string content = File.ReadAllText(path);
If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.
I'm not sure if this is possible for extensions but you could probably use System.IO, like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);
You could also use StreamReader like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
fileText = sr.ReadToEnd();
EDIT:
I think I understand you better now.
The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.
When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).
I'd try searching the SDK files manually (Or with a file crawler).

How to download 10 newest files of type CSV via SFTP using WinSCP?

I use WinSCP quite basically from C#. For example I know that I can download several CSV files from an FTP site using this code:
var remotePath = "some\path*.csv";
var localPath = "some\path";
TransferOperationResult transferResult =
session.GetFiles(remotePath, localPath, false, transferOptions);
But that downloads all the CSVs from the SFTP site. I only want the latest 10. I see from this link: https://winscp.net/eng/docs/script_download_most_recent_file how to get the latest file. And I have found using intellisense that there is a RemoteFileInfoCollection class.
But this class isn't very well documented (or at least not well enough for me to use)
Questions:
How can I use this class?
How can I request 'some' of the CSVs on an SFTP site using seesion.GetFiles(), since the remotePath param is a string and not a list. I know that I could loop through a list of paths and download those from the FTP, is that a reasonable approach? I'm not sure I'd want to call GetFiles() multiple times considering that it seems to specifically be named as file(s), and I know that it does download multiple files at once.
Use the code you have found to download the one latest file and just replace FirstOrDefault with Take and iterate the set to download all selected files.
I'm also using EnumerateRemoteFiles instead of ListDirectory, as it can filter files by filemask on its own.
const string remotePath = "/remote/path";
const string localPath = "C:\local\path";
IEnumerable<RemoteFileInfo> files =
session.EnumerateRemoteFiles(remotePath, "*.csv", EnumerationOptions.None)
.Where(file => !file.IsDirectory)
.OrderByDescending(file => file.LastWriteTime)
.Take(10);
string destPath = Path.Combine(localPath, "*");
foreach (RemoteFileInfo file in files)
{
Console.WriteLine("Downloading {0}...", file.Name);
session.GetFiles(RemotePath.EscapeFileMask(file.FullName), destPath).Check();
}

Play video on Unity without extension

i have this problem, i created an application that play videos but this video haven't extension , so per example i have video like
big_buck_bunny
instead a file like :
big_buck_bunny.mp4
I cant convert this video.
There is a way to play a video from remote without extension?
I have a url like :
D:\\Software\\Marmotta\\marmotta-home\\resources\\88\\95\\43\\big_buck_bunny
Thanks all for help
What about adding the extension at the end of the file?
String path = "D:\\Software\\Marmotta\\marmotta-home\\resources\\88\\95\\43\\big_buck_bunny";
path += #".mp4";
You can use Directory.GetFiles to get all files in a folder filtered to your filename. Be sure to include using System.IO; at thte top of the file.
var path = "D:\\Software\\Marmotta\\marmotta-home\\resources\\88\\95\\43\\big_buck_bunny"
var directory = Path.GetDirectoryName(path);
var filename = Path.GetFileName(path);
string[] files = Directory.GetFiles(directory, filename + ".*", SearchOption.TopDirectoryOnly);
the array files will hold a list of all the files in the folder that started with the name big_buck_bunny, one of those files will be the one you want to use.

Storing MSSQL LocalDB for Application

I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.
After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.
I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.
I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.
I can create a blank file ok to that folder.
Here is the code:
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dvAppDataFolder = appDataFolder + #"\MyApp";
AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);
if (!Directory.Exists(dvAppDataFolder))
Directory.CreateDirectory(dvAppDataFolder);
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
{
File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
}
In addition, Am I going about this the right way?
This line
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.
Finally, you want to write to a file not to a folder
string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
if (!File.Exists(fileName))
{
File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
}
Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use
string appDataFolder = Environment.GetFolderPath
(Environment.SpecialFolder.CommonApplicationData);

Can c# understand this kind of pathing for pointing a file?

..\..\..\ConnectionInterface\ConnectionInterface.vbproj
I mean the "..\"
Because I am reading up a .sln file as a text file to get all the projects in that solution and the problem is this projects inside where in different directories or level.
Here is an example
..\..\..\ConnectionInterface\ConnectionInterface.vbproj
..\States\Components\States.vbproj
any ideas how to get the actual paths of these projects?
Path.GetFullPath(#"..\..\..\ConnectionInterface\ConnectionInterface.vbproj");
This is relative to the current working directory, therefore if the relative reference is not based on the current working directory you will need to define that first.
You can use Path.Combine, but you'll need to know where it's relative to. Basically find the directory that contains the original .sln file (e.g. using Path.GetDirectoryName and Path.GetFullPath) and then use Path.Combine to combine the original directory with the relative file.
For example:
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
string originalFile = "Test.cs";
string relative = #"..\Documents\Foo";
string originalAbsoluteFile = Path.GetFullPath(originalFile);
string originalDirectory = Path.GetDirectoryName(originalAbsoluteFile);
string combined = Path.Combine(originalDirectory, relative);
string combinedAbsolute = Path.GetFullPath(combined);
Console.WriteLine(combinedAbsolute);
}
}
The question isn't very clear, but if you mean does C# understand: C:\SomeDir\InnerDir1\ ..\InnerDir2 to resolve to C:\SomeDir\InnerDir2, then yes, it will work. Just append directory the solution file is in with the relative path, and you are done.

Categories

Resources