Tenho um método onde após uma consulta, crio um arquivo .txt salvando alguns parâmetros. Minha necessidade é obter esse .txt, onde vou tratar esse arquivo em um JavaScript (angularJs) para efetuar o download.
Mas ao tentar obter esse arquivo, tenho um retorno com o erro:
exceptionMessage: "O processo não pode acessar o arquivo 'E:\Projetos\nfs-e\Api\TEXT\users.txt' porque ele está sendo usado por outro processo."
Back end onde crio e salvo o arquivo .txt:
public HttpResponseMessage ObterNotas(UsuarioDTO user)
{
var dataInicial = user.CompetenciaInicial;
var dataFinal = user.CompetenciaFinal;
var listaNotas = this.DbContext.ObterNotasRepo(dataInicial, dataFinal);
string path = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString());
string new_dir = path + "/TEXT/"+ "users.txt";
HttpResponseMessage response = null;
if (!File.Exists(new_dir))
{
response = Request.CreateResponse(HttpStatusCode.Gone);
}
MemoryStream ms = new MemoryStream();
List<string> lista = new List<string>();
using (TextWriter writer = new StreamWriter(new_dir))
{
for (int i = 0; i < listaNotas.Count ; i++)
{
if (i == 0)
{
writer.Write(listaNotas[i].Usuario.CpfCnpj.ToString() + '|' + listaNotas[i].Usuario.RazaoSocial.ToString() + "\r\n");
}
writer.Write(listaNotas[i].NumeroRegistro.ToString() + "\r\n");
}
writer.Flush();
response.Content = new ByteArrayContent(new_dir);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition.FileName = new_dir;
}
return response;
}
JavaScript:
$scope.obterUsuario = function ()
{
$scope.search.prestadorId = authService.authentication.user.codigo;
userService.getUser($scope.search).then(function (result) {
if (result.data.length > 0) {
var data = result.data
console.log(typeof (data));
var headers = result.headers;
headers = headers();
var timeInMs = Date.now();
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", "teste" + '-' + timeInMs + ".txt");
var clickEvent = new MouseEvent("click",
{
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
$modalInstance.dismiss('cancel');
} catch (ex) {
console.log(ex);
}
}
});
}
ms.Close();
, mas não entendi nem pra que oMemoryStream
...File.AppendAllText
? Pelo código, me parece que você tem um background com Java.