FileStream不使用相对路径

时间:2017-05-24 06:07:30

标签: c# filestream

我尝试使用具有相对路径的FileStream,但它无法正常工作。

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

当我使用类似的东西时它正在工作:

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

其余代码(来自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");
        }

我不明白为什么它不起作用,因为FileStream构造函数允许使用相对路径。

2 个答案:

答案 0 :(得分:1)

我假设程序中的文件夹包含子文件夹图像,其中包含图像文件。

\folder\program.exe

\folder\Images\money.jpg

尝试不使用“〜”。

答案 1 :(得分:0)

我也遇到了同样的问题,但我通过使用此代码解决了这个问题,

尝试使用此代码之一,希望它也能解决您的问题。

 #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

第二个

 #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