I have an angular with .net core back end web app. On the front end I have a form. The form is in two parts. The first part is basic info the second is a textarea. Inside of the textarea you can paste part numbers and qtys. For example: MILSDHH, 4 and MSDIJH, 5.
This is then proccesed and put into an array as [{"PartNumber": "MILSDHH", "Qty": 4}]
etc. Each line inside of the textarea is a different object. Once it is sent to the back end, i am having it create text files with that data. Each object must be on a seperate line.
Method that creates text file:
public async Task<OrderDetails> AddOrder(OrderDetails order)
{
await _context.OrderDetails.AddAsync(order);
await SaveAll();
var date = DateTime.Now.ToString("yyyyMMdd");
StringBuilder sb = new StringBuilder();
using (StreamWriter writer = new StreamWriter(($"Y:\\WOL-0{order.CartNumber}-{order.CustomerId}-{date}-085715.txt"), append: true))
{
sb.Append(order);
await writer.WriteAsync($"0{order.CartNumber} {order.LineNumber} {order.PartNumber} {order.Qty} EA {order.SalesLocation} {order.SalesLocation} EA Y ");
}
return order;
}
This brings in that data as order and writes whatever comes in on new lines. The problem lies whenever the page is reloaded and more data is sent. It will only write one line even when two items are sent along with this error.
I know this error would be caused by it trying to write the same file name over again but each file name has a different CartNumber when it is sent to the back end.
I have tried different methods attached to the streamwriter. I have tried writer.Close() and writer.Flush()
along with making the function async and using writer.WriteLineAsync()
The expected result would be it will output multiple lines in the text files every time and not just the first time it is ran.
[SOLVED]
For anyone looking for the answer it was a write issue and the following code solved it.
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public void WriteToFileThreadSafe(OrderDetails order)
{
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try
{
var date = DateTime.Now.ToString("yyyyMMdd");
// Append text to the file
using (StreamWriter sw = new StreamWriter($@"Y:\WOL-0{order.CartNumber}-{order.CustomerId}-{date}-085715.txt", true))
{
sw.WriteLine($"0{order.CartNumber.ToString()} {order.LineNumber.ToString()} {order.PartNumber.ToString()} {order.Qty.ToString()} EA {order.SalesLocation.ToString()} {order.SalesLocation.ToString()} EA Y ");
sw.Close();
}
}
finally
{
// Release lock
_readWriteLock.ExitWriteLock();
}
}