C# saving a file path longer than 260 characters in Windows - c#

I have found some questions here asking the same thing, however the answers have not worked for me. I have a path to another machine on the network where I store files in the following format;
\\machinename\share
We have paths longer than 260 characters. It does not allow me to save these paths when I use this code;
private static void CreateDirectories(string totalPath)
{
var file = new FileInfo(totalPath);
if (file.Directory != null && !file.Directory.Exists)
file.Directory.Create();
}
I have tried using the following notations in the 'totalPath' parameter which don't work if I try to navigate to them in file explorer;
\\?\machinename\share
\\?\UNC\machinename\share
Am I using these paths correctly? Neither of these manage to navigate to the share in file explorer. Is there any other way I can save a file with a path that is longer than 260 characters using C# on windows?
Thanks for any pointers.

Related

Read text file from relative path within project

I am creating a unit test which works using the following exact path:
string path = #"/Users/{username}/Coding/computershare/ChallengeSampleDataSet1.txt";
I read the text from the file by passing this path
string pricesFromFile = System.IO.File.ReadAllText(path);
However, I do not want to hardcode the complete local file path - I want to use the relative path in the project directory.
Therefore I tried the below using other articles on StackOverflow:
string path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ChallengeSampleDataSet1.txt");
But file is not found. How can I fix this so that I'm able to load the file when running the app from another machine?
Edit: the error in console using the second method is
System.IO.FileNotFoundException : Could not find file '/Users/{username}/Coding/computershare/bin/Debug/net5.0/ChallengeSampleDataSet1.txt'.
This should do the trick:
string path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory + #"..\..\..\", "ChallengeSampleDataSet1.txt");
Note the direction of the slash (\)
Since the error is "/Users/{username}/Coding/computershare/bin/Debug/net5.0/ChallengeSampleDataSet1.txt" it indicates that your base directory is /bin/debug/net5.0 down from the root of the code. By double dotting up three levels, you'll be able to find the file in question.

How do I remove version number from file path? - Winforms c#

I am wondering how to remove the version number from a file path in a Windows Form Application.
Currently I wish to save some users application data to a .xml file located in the roaming user profile settings.
To do this I use:
get
{
return Application.UserAppDataPath + "\\FileName.xml";
}
However this returns the following string:
C:\Users\user\AppData\Roaming\folder\subfolder\1.0.0.0\FileName.xml
and I was wondering if there is a non-hack way to remove the version number from the file path so the file path looks like this:
C:\Users\user\AppData\Roaming\folder\subfolder\FileName.xml
Besides parsing the string looking for the last "\", I do not know what to do.
Thanks
Use Directory.GetParent method for this purpose.
get
{
var dir = Directory.GetParent(Application.UserAppDataPath);
return Path.Combine(dir.FullName, "FileName.xml");
}
Also note that I've used Path.Combine instead of concatenating paths, this method helps you to avoid so many problems. Never concatenate strings to create path.

Ioniczip packed files gets corrupted and filenames missplaced

Im having some trouble with IonicZip corrupting the files im packing down with it. At first i thought it was because of the file names, but i have now discovered that this is not the case.
Heres the code i use to pack down things
using (ZipFile pack = new ZipFile())
{
pack.AddProgress += (s, eventArgs) =>
{
if (eventArgs.EventType == ZipProgressEventType.Adding_AfterAddEntry)
{
Regex pattern = new Regex("[(]|[)]|[']|[[]|[]]|[+]");
eventArgs.CurrentEntry.FileName = pattern.Replace(eventArgs.CurrentEntry.FileName, "");
}
};
pack.AddDirectory(defPackageCreationPath + "\\installfiles", "");
pack.Save(outputPath + "\\package.mpp");
}
I used Regex to remove the shown characters from the filenames of the files being packed, as i thought it was because of the filenames they got corrupted somehow. But it is not.
Heres an example. I can pack down this file without problems
[Forge]FurnitureModv2.9.2(FULL).zip
However! If i pack the same file down with a lot of other files, everything screws up..
Take a look at this screenshot of the source folder, where im taking the files from and packing them with the above code, and the extracted folder to the right:
Notice how the file sizes from the source directory doesn't match with what is extracted? Well take a look at the sizes again.. The filenames are not matching those of the source! The file i mentioned before [Forge]FurnitureModv2.9.2(FULL).zip, which is now called ForgeFurnitureModv2.9.2FULL.zip and has gone from 467KB down to 51KB, and if i try to open it, im being told it is corrupted.. But take a look at the TooMuchTNT v2.5.zip file.. This files size is 467KB as the other file was from source, and if i open this file up i get the contents that should have been in [Forge]FurnitureModv2.9.2(FULL).zip !
So all in all i have two problems:
being that the file names doesnt match their contents from source folder
some files gets corrupted, however if i pack a file that gets corrupted without any other file it works fine, and it does not get corrupted.
Can you assist ? Maybe im packing the files wrongly ?

Upload file to Skydrive with special characters and spaces

I am using LiveSDK for Windows Phone 8 (latest SDK version) to upload files:
LiveOperationResult res = await liveClient.BackgroundUploadAsync(_skyDriveFolderId, new Uri("/shared/transfers/" + myLocalFilename, UriKind.Relative), OverwriteOption.Overwrite);
This works fine when myLocalFilename contains only normal ASCII characters like "fileTEST1234.zip". But when the filename contains spaces, or special characters such as "ä", "ß", etc. then an empty (0 Bytes) file is uploaded to SkyDrive (the name of the remote file is correct). So I think there is something going wrong when the local string file name is converted to an Uri object.
One option would be to create a temporary local file copy with a standard name, upload this, and rename it to the other name on SkyDrive.
Are there better ways to fix this problem?

Converting absolute path to relative path C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting path relative to the current working directory?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
For example the path in my code (and in my laptop for the image) is
C:/something/res/images/image1.jpeg
and I want the path in my code to be
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C: partition is etc.
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
I have this code:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
To get a better feel for this, try out the following as a test:
1) create a new visual studio sample project,
2) create an images folder at the same level as the .csproj
3) put some files in the images folder
4) put this sample code in your main method -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
see: Getting path relative to the current working directory?
Uri uri1 = new Uri(#"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(#"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
EDIT
You could also try the following approach. Forget the Directory class giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
String
deletableTarget = #"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours is working, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)

Categories