none
Make file paths from string with file names. RRS feed

  • Question

  • I have a string containing file names in DB . to shoe the image in web page i have to split the string, trim the excess chars and add the directory.


    @foreach (var i in Model.ModelName.Image.Split(new[] { "Filename" }, StringSplitOptions.RemoveEmptyEntries ))
    
    
    <td>  <img src=@i.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0].Trim(new Char[] { ';', ' ', '"', '.', ';', '[', '}', ';', '"', ':', '"', ')', '{' }).Insert(0, "~/Content/UploadedImages/") alt="image"
     style="width:60px;height:23px;" />  </td>
    



    But I am getting an empty string after Trim and the images are not showing up.
    Just a blank box with the alt image text.
    Tried splittting it again, so i could use the RemoveEmptyEntries but not working.
    • Edited by AltFire Wednesday, October 30, 2019 1:28 PM
    Wednesday, October 30, 2019 1:27 PM

Answers

  • Here's the simple, clean approach using JSON.

    class Program
    {
        static void Main ( string[] args )
        {
            var json = "[{\"Filename\":\"ModuleName/00001/00001022_bpwcjw4h2p7sy.jpg\",\"OriginalName\":\"00001022_pap2jxh5645ri_t.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_i7mmmqwspc27i.jpg\",\"OriginalName\":\"demorris - byrd - feQFrMEirNo - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_ji3gneogkdi6q.jpg\",\"OriginalName\":\"jason - leung - KFMYmlGUmcM - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_zq7xe3b7au6jm.jpg\",\"OriginalName\":\"kevin - mueller - ykrpdbqFMQM - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_l2q3yrd7chhga.jpg\",\"OriginalName\":\"david - dvoracek - 19 - rJG0QENU - unsplash.jpg\"}" +
                        "]";
    
            //Convert to JSON 
            var data = JsonConvert.DeserializeObject<IEnumerable<MyData>>(json);
    
            //Get the filenames and concat with the target path
            var targetPath = "~/Content/UploadedImages/";
    
            //Completely ignoring the issue of paths have slashes...
            var filenames = data.Select(d => targetPath + d.Filename);
            foreach (var filename in filenames)
                Console.WriteLine(filename);
        }
    }
    
    class MyData
    {
        public string Filename { get; set; }
        public string OriginalName { get; set; }
    }
    It hides all the gory details of what can actually appear in a JSON file, case conversion, spacing, etc. Things you'd have to do manually if you were going to use split/trim.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by AltFire Thursday, October 31, 2019 8:50 AM
    Wednesday, October 30, 2019 6:05 PM
    Moderator

All replies

  • Questions related to web development can be posted in the ASP.NET forums.

    On the C# side related to split/trim your first split doesn't look correct to me. It would be really useful if you could post the contents of your `Image` property because I'm not convinced it has the value formatted the way you are splitting it. You are taking an Image (string I assume) and splitting it based upon the string `Filename`. So here's what you'd get.

    static void Main ( string[] args )
    {
        var values = new[]
        {
            @"C:\Temp\Test",
            @"FirstFilenameLast",
            @"FirstfilenameLast",
            @"FirstFilename",
        };
    
        foreach (var i in values)
        {
            //Note that this is case sensitive
            var tokens = i.Split(new[] { "Filename" }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine($"{i} = {String.Join(", ", tokens)}");                    
        };
    }
    
    //FirstFilenameLast = First, Last
    //FirstfilenameLast = FirstfilenameLast
    //FirstFilename = First
    Given your second set of split/trims it looks like you actually have formatted data and you're trying to use split/trim to find the objects which isn't a good idea. Posting the actual format of `Image` would let us provide a better approach such as using a JSON deserializer or even regular expressions.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, October 30, 2019 2:14 PM
    Moderator
  • Hi

    This is a vlaue from the a string in DB that has the filenames. Its just random images from copyright free images. They get added from a multiple image file uploader component.

    [{"Filename":"ModuleName/00001/00001022_bpwcjw4h2p7sy.jpg","OriginalName":"00001022_pap2jxh5645ri_t.jpg"},{"Filename":"ModuleName/00001/00001022_i7mmmqwspc27i.jpg","OriginalName":"demorris-byrd-feQFrMEirNo-unsplash.jpg"},{"Filename":"ModuleName/00001/00001022_ji3gneogkdi6q.jpg","OriginalName":"jason-leung-KFMYmlGUmcM-unsplash.jpg"},{"Filename":"ModuleName/00001/00001022_zq7xe3b7au6jm.jpg","OriginalName":"kevin-mueller-ykrpdbqFMQM-unsplash.jpg"},{"Filename":"ModuleName/00001/00001022_l2q3yrd7chhga.jpg","OriginalName":"david-dvoracek-19-rJG0QENU-unsplash.jpg"}]

    I need to find the image and add it to the page.

    So i split on Filename, and split on ',', then Trim. it should come as a bare string so  why can't I concat it on to path 

    "~/Content/UploadedImages/"

    and derive full 'src' value?

    Wednesday, October 30, 2019 2:37 PM
  • That's JSON, you really shouldn't be using string parsing for it. Use a JSON deserializer like JSON.NET. 

    Also, this isn't a web dev forum but I cannot let this go by without warning you. You should absolutely not be doing any of this in your view. That completely and utterly defeats the purpose of MVC. A view is solely for rendering data. As soon as you start adding anything more than Model.Property in your view you are doing something wrong. All this logic needs to be in the model. So I'm going to completely ignore your view code (and hence the connection to the web).

    I have to go right now. I'll be back to post the string code later but really consider using JSON parser instead. It is more accurate, faster and cleaner.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, October 30, 2019 4:00 PM
    Moderator
  • Its for a PDF report not an actual web page, so things arent working like the dev tools, making it more difficult.

    Thanks in advance.

    Wednesday, October 30, 2019 4:37 PM
  • Here's the simple, clean approach using JSON.

    class Program
    {
        static void Main ( string[] args )
        {
            var json = "[{\"Filename\":\"ModuleName/00001/00001022_bpwcjw4h2p7sy.jpg\",\"OriginalName\":\"00001022_pap2jxh5645ri_t.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_i7mmmqwspc27i.jpg\",\"OriginalName\":\"demorris - byrd - feQFrMEirNo - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_ji3gneogkdi6q.jpg\",\"OriginalName\":\"jason - leung - KFMYmlGUmcM - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_zq7xe3b7au6jm.jpg\",\"OriginalName\":\"kevin - mueller - ykrpdbqFMQM - unsplash.jpg\"}," +
                        "{\"Filename\":\"ModuleName/00001/00001022_l2q3yrd7chhga.jpg\",\"OriginalName\":\"david - dvoracek - 19 - rJG0QENU - unsplash.jpg\"}" +
                        "]";
    
            //Convert to JSON 
            var data = JsonConvert.DeserializeObject<IEnumerable<MyData>>(json);
    
            //Get the filenames and concat with the target path
            var targetPath = "~/Content/UploadedImages/";
    
            //Completely ignoring the issue of paths have slashes...
            var filenames = data.Select(d => targetPath + d.Filename);
            foreach (var filename in filenames)
                Console.WriteLine(filename);
        }
    }
    
    class MyData
    {
        public string Filename { get; set; }
        public string OriginalName { get; set; }
    }
    It hides all the gory details of what can actually appear in a JSON file, case conversion, spacing, etc. Things you'd have to do manually if you were going to use split/trim.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by AltFire Thursday, October 31, 2019 8:50 AM
    Wednesday, October 30, 2019 6:05 PM
    Moderator