Zet
Zet

Reputation: 571

FileStream is not working with relative path

I'm trying to use a FileStream with a relative path but it is not working.

 var pic = ReadFile("~/Images/money.png");

It is working when I use something like:

var p = GetFilePath();
var pic = ReadFile(p);

the rest of the code(from SO):

public static byte[] ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;  // sum is a buffer offset for next reading
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }

        public string GetFilePath()
        {
            return HttpContext.Current.Server.MapPath("~/Images/money.png");
        }

I don't get why it is not working because the FileStream constructor allow using relative path.

Upvotes: 0

Views: 2269

Answers (2)

DrNachtschatten
DrNachtschatten

Reputation: 412

I'm assuming the folder in your program has the subfolder images, which contains your image file.

\folder\program.exe

\folder\Images\money.jpg

Try without the "~".

Upvotes: 1

Jay
Jay

Reputation: 19

I also had the same issue but I solved it by using this code,

Try one of this code, hope it will solve your issue too.

 #region GetImageStream
    public static Stream GetImageStream(string Image64string)
    {
        Stream imageStream = new MemoryStream();
        if (!string.IsNullOrEmpty(Image64string))
        {
            byte[] imageBytes = Convert.FromBase64String(Image64string.Substring(Image64string.IndexOf(',') + 1));
            using (Image targetimage = BWS.AWS.S3.ResizeImage(System.Drawing.Image.FromStream(new MemoryStream(imageBytes, false)), new Size(1600, 1600), true))
            {
                targetimage.Save(imageStream, ImageFormat.Jpeg);
            }
        }
        return imageStream;
    }

    #endregion

2nd one

 #region GetImageStream
    public static Stream GetImageStream(Stream stream)
    {
        Stream imageStream = new MemoryStream();
        if (stream != null)
        {
            using (Image targetimage = BWS.AWS.S3.ResizeImage(System.Drawing.Image.FromStream(stream), new Size(1600, 1600), true))
            {
                targetimage.Save(imageStream, ImageFormat.Jpeg);
            }
        }
        return imageStream;
    }

    #endregion

Upvotes: 0

Related Questions