Catgirl21
Catgirl21

Reputation: 37

How to trim a file name to not exceed the maximum file path size

I am making an image downloader that should be able to name a downloaded file with tags. However, sometimes there are too many tags and I get an exception because the filename is too long.

The file path is: my .exe path + ./out/ directory + tags + extension

I want a piece of code that would let me trim a filename string if its full path exceeds the maximum length and keep an extension.

I have already got some code but it doesn't work properly and I don't think it is clean enough.

string Truncate(string value, int maxChars)
{
    return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}
private async void downloadImage(string url, string tags, string rating)
        {
            string fullpath = "./out/" + rating + tags + ExtFromURL(url);
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            fullpath = r.Replace(fullpath, "");

            string shortPath = Path.GetFullPath("./out/" + rating + ExtFromURL(url));
            string extension = fullpath.Substring(fullpath.Length - 5);
            if (fullpath.Length > 259)
                fullpath = Truncate(fullpath, 259 - shortPath.Length - 4);
            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +
                                      "Windows NT 5.2; .NET CLR 1.0.3705;)");
                    await wc.DownloadFileTaskAsync(new System.Uri(url), fullpath + extension);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

Upvotes: 0

Views: 940

Answers (1)

Christopher
Christopher

Reputation: 9804

The file path is: my .exe path + ./out/ directory + tags + extension

There is no sensible way to do that. If you do not want your filename to get to long, just do not add stuff to it in the first place. But even then it might be to long, because someone picked a really, really long path as their out directory.

Usually such directories are in the user profile. While that makes the very reliable place to have write rights, that also makes it exceeding propable the fully qualified path is to long. I have been running into lenght issues just making backup copies of those folders!

This is a plain old Exogenous excetpions. There is nothing you can do about it, except catching it and telling the user about it. As long as the user can pick the out folder - and maybe wich tags to add - this is not jour problem to fix.

But do take care to only catch the exact exceptions you can actually handle. catch (Exception ex) should be avoided in production code.

Upvotes: 2

Related Questions