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

..\..\..\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.

Related

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

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.

C# winforms get nth folders from path

I've got an absolute path available to me. Say: C:/Program/CoreFiles/Folder1/Folder2/File.txt.
I need to copy that file to C:/Program/Projects/ProjectName/ but it needs to keep Folder1/Folder2/File.txt intact. So the end result should be C:/Program/Projects/ProjectName/Folder1/Folder2/File.txt.
My first attempt at solving this was to try and get the relative path between 2 absolute paths. Found Path.GetRelativePath(string, string) which obviously didn't help as it wasn't meant for WinForms. It would mess up anyway as the final result would be C:/Program/Projects/ProjectName/CoreFiles/Folder1/Folder2/File.txt.
The target directory is empty and I don't know the relative path to copy beforehand other than somehow getting that info out of the absolute path. Since File.Copy won't create folders that don't exist yet, I need to create them first. So how do I get the path that leads up to the file from the CoreFiles directory out of the absolute path?
The only working solution I can come up with is using regex to just replace CoreFiles with Projects/ProjectName in the path string and work with that. But that somehow seems the wrong approach.
Since you can't use Path.GetRelativePath. I suggest looking at another answer that describes how to do this yourself.
Like here...
How to get relative path from absolute path
Using the method in that answer, you can do the rest of your task as shown below.
string sourcePath = "C:/Program/CoreFiles/Folder1/Folder2/File.txt";
string sourceRoot = "C:/Program/CoreFiles/";
string destinationRoot = "C:/Program/Projects/ProjectName/";
// Use built-in .NET Path.GetRelativePath if you can. Otherwise use a custom function. Like here https://stackoverflow.com/a/340454/1812944
string relativePath = MakeRelativePath(sourceRoot, sourcePath);
// Combine the paths, and make the directory separators all the same.
string destinationPath = Path.GetFullPath(Path.Combine(destinationRoot, relativePath));
// Create nested folder structure for your files.
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
// Copy the file over.
File.Copy(sourcePath, destinationPath);

c# FileInfo class being used in SSIS Script Task Directory.GetFiles SearchOption.TopDirectoryOnly being ignored

I am using the following Script Task to enumerate over a file directory, then pull a list of files and load them into a Recordset Destination. I don't want to drill down past the directory I specified #"E:\Data Warehouse\Imports\TIMECLOCK" in my search. There's a subsequent folder inside TIMECLOCK called PROCESSED, where it's supposed to move the files into later. So I'm only trying to grab the ones in the folder above, TIMECLOCK. So I used the SearchOption.TopDirectoryOnly in the Directory.GetFiles function, but it's drilling down past that to the PROCESSED folder, as evidenced by my Data Viewer (see Data View screenshot after the code). At first I was using a variable to pass in the search directory, but it was doing the same thing, so I explicitly declared the search directory, and it's still not working. I don't know what I'm doing wrong!
#region Namespaces
using System;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
#endregion
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent{
public override void CreateNewOutputRows()
{
string sourceDirectory = #"E:\Data Warehouse\Imports\TIMECLOCK";
string searchFileName = "Business Units GL Segments_Sent Weekly*";
string[] files = Directory.GetFiles(sourceDirectory, searchFileName, SearchOption.TopDirectoryOnly);
FileInfo fileInfo = new FileInfo(sourceDirectory);
foreach (string file in files)
{
String FileFullPath = Path.GetFullPath(file);
fileInfo = new FileInfo(FileFullPath);
OrderedFilesBuffer.AddRow();
OrderedFilesBuffer.FileName = fileInfo.Name;
OrderedFilesBuffer.FileDate = fileInfo.LastWriteTime;
OrderedFilesBuffer.FilePath = fileInfo.FullName;
}
}
}
I am marking as answered because I am still completely not sure why this was happening, and I ultimately decided what I was trying to reproduce with writing the values to (2) file objects, then merging and getting a unique list of files between them to process, was really just a simple File Move task. I was writing this for a client who originally designed it in Pentaho Data Integration that way and was reproducing it exactly in SSIS, when it was not really necessary. I think since I was running both of these extractions simultaneously in the same Control Flow, it was using the same file path for both because of a cache issue of some sort and ignoring the TopDirectoryOnly. At any rate, I trashed it and re-did the whole thing.

Reading files using system.io?

Could do with some help with this question.I am using the system.io, and I have to do things which require files to be moved, grouped, renamed. .
Working in command line application using c# so far I have moved some files from one directory to another, I now need to group some pdf files like so - B-12345 1.pdf, B-12345 2.pdf, B-12345 3.pdf, B-12345 4.pdf.I have been told I dont need to physically group them together just for the purposes of ensuring I only create one job per project reference(b-1234).
To give you a bit of background info on what im doing after these files are grouped I need to create a record in the job table sql database.But thats another question for another day just thought id give you some more info.
Mainly I just need info on how to read files that are in a file directory and grouping files, this would be very beneficial to me.?
To make the question a bit clearer this is the order in tasks should be done in the command line app.
Read files in directory (I have moved them so unsure on this?)
Group by project no (unsure)
Create job record in sql db
Move and rename file to correct location
Thanks in advance
My code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
public class MoveForProcessing
{
static void Main()
{
// move cad jobs to processing directory and delete former folder, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Ben\My Documents\Temp\", #"C:\Users\Ben\My Documents\Processing\");
}
}
You could first declare a DirectoryInfo class of the dirctory in question
private System.IO.DirectoryInfo dir = System.IO.DirectoryInfo.Open(#"path");
Then get an array of FileInfo objects for each file in the directory
private FileInfo[] files = dir.GetFiles();
You could also put a wildcard string into GetFiles() if you want only certain file types
private FileInfo[] files = dir.GetFiles("*.pdf");
Then you can increment through the array doing whatever you need with each FileInfo object
foreach(FileInfo f in files)
{
f.Move(); // or whatever you need to do
}

Setting Log file path in app.config

I have one requirement that i have to place the log file in the same directory of solution. That is my solution is placed in [drive]\work\Project1\solution file. But i have to create my log file to [drive]\work\Project1\Log\log.log. How it can be set in app.config file.
please help me. thanks in advance...
If you assume the Visual Studio directory layout, then your program will be in [drive]\work\Project1\bin\Release\ (or possibly \Debug). And you want your log file to be in the directory [drive]\work\Project1\Log.
That directory is the same as [drive]\work\Project1\bin\Release\..\..\Log\
So, one way to do it would be to get the executing program's full path name, extract the directory, and append ....\Log. Like this:
using System.IO; // for Path class
using System.Windows.Forms; // for Application.ExecutablePath
...
string GetLogFilePath()
{
string ProgramPath = Path.GetDirectory(Application.ExecutablePath);
string LogPath = Path.Combine(ProgramPath, #"\..\..\Log\");
return LogPath;
}
If you don't want to include System.Windows.Forms, you can instead include System.Reflection and get the assembly's location with Assembly.GetExecutingAssembly().Location.

Categories

Resources