Domanda

I have a service that I am using for excel file imports, and the implementation is shown below:

[Attributes.ImportFileExtension(Extension=".xls")]
[Attributes.ImportFileExtension(Extension=".xlt")]
[Attributes.ImportFileExtension(Extension=".xlsx")]
public class ExcelImportService:FileImportServiceBase,IFileImportService
{
    public DataSet Import(System.IO.Stream fileStream)
    {
        IExcelDataReader excelReader = null;
        switch (Extension)
        {
            case ".xls":
            case ".xlt":
                excelReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
                break;
            case ".xlsx":
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
                break;
        }
        excelReader.IsFirstRowAsColumnNames = true;
        DataSet dataSet = excelReader.AsDataSet();
        return dataSet;
    }
}

Additionally, I have the following code that is calling this service through a factory that is being created. The code for invoking this service is shown below:

        try
        {
            var extension = Path.GetExtension(dialog.FileName);
            var importService = FileImportServiceFactory.Create(extension);
            var stream = dialog.OpenFile();
            var data = importService.Import(stream);
            stream.Close();
            stream.Dispose();

            var result = new FileImportedMessage { Data = data };
            result.Dispatch();
        }
        catch (Exception e)
        {
            MessageDispatcher.Dispatch(new ExceptionMessage(e));
        }

The import works find UNLESS the file is open while it is being imported.

I have two questions:

1)What is the best practice/strategy for handling this situation?

2)How do I, or should I handle this?

È stato utile?

Soluzione

the problem is you are opening the file in read only mode and when adder program opens it in read write mode it locks the file.

You only have two options.

1- greedy way open the file in read write mode locking it only for your program.

2- (only if the file is not to big) read the complete file to a memory stream and processing it from there.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top