2017-02-08 168 views
0

我在Canvas元素中有一個圖像文件,我在代碼中在asp.net中獲取。現在我想將它保存到我的項目中的文件夾中,但文件流始終將其保存到C盤。我該怎麼辦?文件流文件保存

[WebMethod()] 
public void SaveUser(string imageData) 
{ 
    //Create image to local machine. 
    string fileNameWitPath = path + "4200020789506" + ".png"; 

    using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create)) 
    { 
     using (BinaryWriter bw = new BinaryWriter(fs)) 
     { 
      byte[] data = Convert.FromBase64String(imageData); 
      bw.Write(data); 
      bw.Close(); 
     } 
    } 
    // Save fileNameWitPath variable to Database. 
} 
+0

'path'是否有值? –

+0

yes path有一個值指向C:\ Demo文件夾 – user3132148

+0

它是'C:\ Demo'還是'C:\ Demo \'?這可能是你直接保存到C: –

回答

0

這就是我所做的,它運作良好。對於你來說,filePath/filename = fileNameWitPath。爲每個文件執行此操作。希望對你有效。如果您需要更多信息,我很樂意提供幫助。

using (var stream = File.Create(filePath + filename)) 
{ 
     attachment.ContentObject.DecodeTo(stream, cancel.Token); 
} 
1

我只能想象你的path變量指向你的C:\驅動器。

您需要設置PATH變量等於你想要的位置,例如:

public void SaveUser(string imageData) 
    { 
     path = @"C:\YourCustomFolder\"; // your path needs to point to the Directory you want to save 
     //Create image to local machine. 
     string fileNameWitPath = path + "4200020789506" + ".png"; 

     //chekc if directory exist, if not, create 
     if (!Directory.Exists(path)) 
      Directory.CreateDirectory(path); 

     using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create)) 
     { 
      using (BinaryWriter bw = new BinaryWriter(fs)) 
      { 
       byte[] data = Convert.FromBase64String(imageData); 
       bw.Write(data); 
       bw.Close(); 
      } 
     } 
     // Save fileNameWitPath variable to Database. 
    } 

我還包括一個檢查,看看你的目錄存在,如果沒有,它會創建一個在您的C驅動器上名爲'YourCustomFolder'的文件夾中,它將保存圖像。

如果您想將圖像保存到一個文件夾在您的項目,我會建議使用Server.MapPath(~/YourFolderInApplication)

1

下面是我如何保存在我的項目目錄中的文件到文件夾Images一個例子。

var fileName = "4200020789506.png"; 
var base64String = SOME_REALLY_LONG_STRING; 

using (var s = new MemoryStream(Convert.FromBase64String(base64String))) 
using (var f = new FileStream(Path.Combine(Server.MapPath("~/Images"), fileName), FileMode.Create, FileAccess.Write)) 
{ 
    s.CopyTo(f); 
}