WPF
[WPF] WebView2 파일 다운로드 경로 커스터마이징 하는법 (feat. C#)
pingu
2022. 12. 22. 10:51
반응형
지난번에 사용해본 새로운 인터넷 브라우저 WebView2의 다운로드 이벤트 처리하는 것을 다뤄봄
웹뷰2 방식을 사용한 인터넷 브라우저에서 파일을 다운로드 하는 경우,
자동으로 다운로드 폴더에 파일이 저장되는데
이때 FileSaveDialog 를 사용하여 사용자가 원하는 경로에 파일 저장할 수 있도록 커스터마이징 한 방식
파일 형식과 파일명은 다운로드할 때 자동으로 지정되는 형식과 파일명을 그대로 사용하였다
따라서 아래 방식으로는 저장할 때 파일 형식은 변경이 불가능한데 파일명만 가능한 상태로
형식 변경을 원하면 따로 수정해서 사용해줘야함
//웹뷰2 저장 경로 지정 커스터마이징
static string webSaveFilePath = "";
private bool? getSaveWebFilePath(string filePath)
{
try
{
string fileExt = System.IO.Path.GetExtension(filePath).ToString();
int strLen = fileExt.Length;
webSaveFilePath = null;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = System.IO.Path.GetFileName(filePath).ToString();
dlg.Filter = fileExt.Substring(1, strLen-1) + "|*" + System.IO.Path.GetExtension(filePath).ToString();
bool? result = dlg.ShowDialog();
if (result == true)
{
webSaveFilePath = System.IO.Path.GetFullPath(dlg.FileName).ToString();
}
return result;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
return false;
}
}
//웹뷰2 다운로드 이벤트 발생
private void WB_DownloadStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2DownloadStartingEventArgs e)
{
Microsoft.Web.WebView2.Core.CoreWebView2Deferral deferral = e.GetDeferral();
string filePath = e.DownloadOperation.ResultFilePath;
bool? saveResult = getSaveWebFilePath(filePath);
//저장 취소 또는 오류 발생 시 저장 하지않음
if (saveResult == null || saveResult == false)
{
e.DownloadOperation.Cancel();
return;
}
System.Threading.SynchronizationContext.Current.Post((_) =>
{
using (deferral)
{
// Hide the default download dialog.
e.Handled = true;
e.ResultFilePath = webSaveFilePath;
}
}, null);
}
반응형