SftpTests.cs 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [TestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. CollectionAssert.AreEqual(newContent1Bytes, actualContent1);
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. CollectionAssert.AreEqual(newContent2Bytes, actualContent2);
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual("No such file", ex.Message);
  221. }
  222. finally
  223. {
  224. fs?.Dispose();
  225. if (client.Exists(remoteFile))
  226. {
  227. client.DeleteFile(remoteFile);
  228. }
  229. }
  230. }
  231. }
  232. [TestMethod]
  233. public void Sftp_Create_FileDoesNotExist()
  234. {
  235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  236. {
  237. client.BufferSize = 512 * 1024;
  238. client.Connect();
  239. var remoteFile = GenerateUniqueRemoteFileName();
  240. if (client.Exists(remoteFile))
  241. {
  242. client.DeleteFile(remoteFile);
  243. }
  244. try
  245. {
  246. using (var imageStream = GetData("resources.issue #70.png"))
  247. {
  248. using (var fs = client.Create(remoteFile))
  249. {
  250. imageStream.CopyTo(fs);
  251. }
  252. using (var memoryStream = new MemoryStream())
  253. {
  254. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  255. memoryStream.Position = 0;
  256. imageStream.Position = 0;
  257. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  258. }
  259. }
  260. }
  261. finally
  262. {
  263. if (client.Exists(remoteFile))
  264. {
  265. client.DeleteFile(remoteFile);
  266. }
  267. }
  268. }
  269. }
  270. [TestMethod]
  271. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  272. {
  273. var initialContent = "\u0100ert & Ann";
  274. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  275. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  276. Environment.NewLine;
  277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  278. {
  279. client.Connect();
  280. var remoteFile = GenerateUniqueRemoteFileName();
  281. if (client.Exists(remoteFile))
  282. {
  283. client.DeleteFile(remoteFile);
  284. }
  285. try
  286. {
  287. client.WriteAllText(remoteFile, initialContent);
  288. client.AppendAllLines(remoteFile, linesToAppend);
  289. var text = client.ReadAllText(remoteFile);
  290. Assert.AreEqual(expectedContent, text);
  291. // ensure we didn't write an UTF-8 BOM
  292. using (var fs = client.OpenRead(remoteFile))
  293. {
  294. var firstByte = fs.ReadByte();
  295. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  296. }
  297. }
  298. finally
  299. {
  300. if (client.Exists(remoteFile))
  301. {
  302. client.DeleteFile(remoteFile);
  303. }
  304. }
  305. }
  306. }
  307. [TestMethod]
  308. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  309. {
  310. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  311. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  312. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  313. {
  314. client.Connect();
  315. if (client.Exists(remoteFile))
  316. {
  317. client.DeleteFile(remoteFile);
  318. }
  319. try
  320. {
  321. client.AppendAllLines(remoteFile, linesToAppend);
  322. Assert.Fail();
  323. }
  324. catch (SftpPathNotFoundException ex)
  325. {
  326. Assert.IsNull(ex.InnerException);
  327. Assert.AreEqual("No such file", ex.Message);
  328. }
  329. finally
  330. {
  331. if (client.Exists(remoteFile))
  332. {
  333. client.DeleteFile(remoteFile);
  334. }
  335. }
  336. }
  337. }
  338. [TestMethod]
  339. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  340. {
  341. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  342. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  343. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  344. {
  345. client.Connect();
  346. var remoteFile = GenerateUniqueRemoteFileName();
  347. if (client.Exists(remoteFile))
  348. {
  349. client.DeleteFile(remoteFile);
  350. }
  351. try
  352. {
  353. client.AppendAllLines(remoteFile, linesToAppend);
  354. var text = client.ReadAllText(remoteFile);
  355. Assert.AreEqual(expectedContent, text);
  356. // ensure we didn't write an UTF-8 BOM
  357. using (var fs = client.OpenRead(remoteFile))
  358. {
  359. var firstByte = fs.ReadByte();
  360. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  361. }
  362. }
  363. finally
  364. {
  365. if (client.Exists(remoteFile))
  366. {
  367. client.DeleteFile(remoteFile);
  368. }
  369. }
  370. }
  371. }
  372. [TestMethod]
  373. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  374. {
  375. var initialContent = "\u0100ert & Ann";
  376. var contentToAppend = "Forever&\u0116ver";
  377. var expectedContent = initialContent + contentToAppend;
  378. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  379. {
  380. client.Connect();
  381. var remoteFile = GenerateUniqueRemoteFileName();
  382. if (client.Exists(remoteFile))
  383. {
  384. client.DeleteFile(remoteFile);
  385. }
  386. try
  387. {
  388. client.WriteAllText(remoteFile, initialContent);
  389. client.AppendAllText(remoteFile, contentToAppend);
  390. var text = client.ReadAllText(remoteFile);
  391. Assert.AreEqual(expectedContent, text);
  392. // ensure we didn't write an UTF-8 BOM
  393. using (var fs = client.OpenRead(remoteFile))
  394. {
  395. var firstByte = fs.ReadByte();
  396. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  397. }
  398. }
  399. finally
  400. {
  401. if (client.Exists(remoteFile))
  402. {
  403. client.DeleteFile(remoteFile);
  404. }
  405. }
  406. }
  407. }
  408. [TestMethod]
  409. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  410. {
  411. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  412. var contentToAppend = "Forever&\u0116ver";
  413. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  414. {
  415. client.Connect();
  416. if (client.Exists(remoteFile))
  417. {
  418. client.DeleteFile(remoteFile);
  419. }
  420. try
  421. {
  422. client.AppendAllText(remoteFile, contentToAppend);
  423. Assert.Fail();
  424. }
  425. catch (SftpPathNotFoundException ex)
  426. {
  427. Assert.IsNull(ex.InnerException);
  428. Assert.AreEqual("No such file", ex.Message);
  429. }
  430. finally
  431. {
  432. if (client.Exists(remoteFile))
  433. {
  434. client.DeleteFile(remoteFile);
  435. }
  436. }
  437. }
  438. }
  439. [TestMethod]
  440. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  441. {
  442. var contentToAppend = "Forever&\u0116ver";
  443. var expectedContent = contentToAppend;
  444. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  445. {
  446. client.Connect();
  447. var remoteFile = GenerateUniqueRemoteFileName();
  448. if (client.Exists(remoteFile))
  449. {
  450. client.DeleteFile(remoteFile);
  451. }
  452. try
  453. {
  454. client.AppendAllText(remoteFile, contentToAppend);
  455. var text = client.ReadAllText(remoteFile);
  456. Assert.AreEqual(expectedContent, text);
  457. // ensure we didn't write an UTF-8 BOM
  458. using (var fs = client.OpenRead(remoteFile))
  459. {
  460. var firstByte = fs.ReadByte();
  461. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  462. }
  463. }
  464. finally
  465. {
  466. if (client.Exists(remoteFile))
  467. {
  468. client.DeleteFile(remoteFile);
  469. }
  470. }
  471. }
  472. }
  473. [TestMethod]
  474. public void Sftp_AppendText_NoEncoding_ExistingFile()
  475. {
  476. var initialContent = "\u0100ert & Ann";
  477. var contentToAppend = "Forever&\u0116ver";
  478. var expectedContent = initialContent + contentToAppend;
  479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  480. {
  481. client.Connect();
  482. var remoteFile = GenerateUniqueRemoteFileName();
  483. if (client.Exists(remoteFile))
  484. {
  485. client.DeleteFile(remoteFile);
  486. }
  487. try
  488. {
  489. client.WriteAllText(remoteFile, initialContent);
  490. using (var sw = client.AppendText(remoteFile))
  491. {
  492. sw.Write(contentToAppend);
  493. }
  494. var text = client.ReadAllText(remoteFile);
  495. Assert.AreEqual(expectedContent, text);
  496. // ensure we didn't write an UTF-8 BOM
  497. using (var fs = client.OpenRead(remoteFile))
  498. {
  499. var firstByte = fs.ReadByte();
  500. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  501. }
  502. }
  503. finally
  504. {
  505. if (client.Exists(remoteFile))
  506. {
  507. client.DeleteFile(remoteFile);
  508. }
  509. }
  510. }
  511. }
  512. [TestMethod]
  513. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  514. {
  515. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  516. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  517. {
  518. client.Connect();
  519. if (client.Exists(remoteFile))
  520. {
  521. client.DeleteFile(remoteFile);
  522. }
  523. StreamWriter sw = null;
  524. try
  525. {
  526. sw = client.AppendText(remoteFile);
  527. Assert.Fail();
  528. }
  529. catch (SftpPathNotFoundException ex)
  530. {
  531. Assert.IsNull(ex.InnerException);
  532. Assert.AreEqual("No such file", ex.Message);
  533. }
  534. finally
  535. {
  536. sw?.Dispose();
  537. if (client.Exists(remoteFile))
  538. {
  539. client.DeleteFile(remoteFile);
  540. }
  541. }
  542. }
  543. }
  544. [TestMethod]
  545. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  546. {
  547. var contentToAppend = "\u0100ert & Ann";
  548. var expectedContent = contentToAppend;
  549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  550. {
  551. client.Connect();
  552. var remoteFile = GenerateUniqueRemoteFileName();
  553. if (client.Exists(remoteFile))
  554. {
  555. client.DeleteFile(remoteFile);
  556. }
  557. try
  558. {
  559. using (var sw = client.AppendText(remoteFile))
  560. {
  561. sw.Write(contentToAppend);
  562. }
  563. // ensure we didn't write an UTF-8 BOM
  564. using (var fs = client.OpenRead(remoteFile))
  565. {
  566. var firstByte = fs.ReadByte();
  567. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  568. }
  569. }
  570. finally
  571. {
  572. if (client.Exists(remoteFile))
  573. {
  574. client.DeleteFile(remoteFile);
  575. }
  576. }
  577. }
  578. }
  579. [TestMethod]
  580. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  581. {
  582. var initialContent = "\u0100ert & Ann";
  583. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  584. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  585. Environment.NewLine;
  586. var encoding = GetRandomEncoding();
  587. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  588. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  589. {
  590. client.Connect();
  591. var remoteFile = GenerateUniqueRemoteFileName();
  592. if (client.Exists(remoteFile))
  593. {
  594. client.DeleteFile(remoteFile);
  595. }
  596. try
  597. {
  598. client.WriteAllText(remoteFile, initialContent, encoding);
  599. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  600. var text = client.ReadAllText(remoteFile, encoding);
  601. Assert.AreEqual(expectedContent, text);
  602. var actualBytes = client.ReadAllBytes(remoteFile);
  603. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  604. }
  605. finally
  606. {
  607. if (client.Exists(remoteFile))
  608. {
  609. client.DeleteFile(remoteFile);
  610. }
  611. }
  612. }
  613. }
  614. [TestMethod]
  615. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  616. {
  617. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  618. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  619. var encoding = GetRandomEncoding();
  620. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  621. {
  622. client.Connect();
  623. if (client.Exists(remoteFile))
  624. {
  625. client.DeleteFile(remoteFile);
  626. }
  627. try
  628. {
  629. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  630. Assert.Fail();
  631. }
  632. catch (SftpPathNotFoundException ex)
  633. {
  634. Assert.IsNull(ex.InnerException);
  635. Assert.AreEqual("No such file", ex.Message);
  636. }
  637. finally
  638. {
  639. if (client.Exists(remoteFile))
  640. {
  641. client.DeleteFile(remoteFile);
  642. }
  643. }
  644. }
  645. }
  646. [TestMethod]
  647. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  648. {
  649. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  650. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  651. var encoding = GetRandomEncoding();
  652. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  653. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  654. {
  655. client.Connect();
  656. var remoteFile = GenerateUniqueRemoteFileName();
  657. if (client.Exists(remoteFile))
  658. {
  659. client.DeleteFile(remoteFile);
  660. }
  661. try
  662. {
  663. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  664. var text = client.ReadAllText(remoteFile, encoding);
  665. Assert.AreEqual(expectedContent, text);
  666. var actualBytes = client.ReadAllBytes(remoteFile);
  667. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  668. }
  669. finally
  670. {
  671. if (client.Exists(remoteFile))
  672. {
  673. client.DeleteFile(remoteFile);
  674. }
  675. }
  676. }
  677. }
  678. [TestMethod]
  679. public void Sftp_AppendAllText_Encoding_ExistingFile()
  680. {
  681. var initialContent = "\u0100ert & Ann";
  682. var contentToAppend = "Forever&\u0116ver";
  683. var expectedContent = initialContent + contentToAppend;
  684. var encoding = GetRandomEncoding();
  685. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  686. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  687. {
  688. client.Connect();
  689. var remoteFile = GenerateUniqueRemoteFileName();
  690. if (client.Exists(remoteFile))
  691. {
  692. client.DeleteFile(remoteFile);
  693. }
  694. try
  695. {
  696. client.WriteAllText(remoteFile, initialContent, encoding);
  697. client.AppendAllText(remoteFile, contentToAppend, encoding);
  698. var text = client.ReadAllText(remoteFile, encoding);
  699. Assert.AreEqual(expectedContent, text);
  700. var actualBytes = client.ReadAllBytes(remoteFile);
  701. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  702. }
  703. finally
  704. {
  705. if (client.Exists(remoteFile))
  706. {
  707. client.DeleteFile(remoteFile);
  708. }
  709. }
  710. }
  711. }
  712. [TestMethod]
  713. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  714. {
  715. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  716. const string contentToAppend = "Forever&\u0116ver";
  717. var encoding = GetRandomEncoding();
  718. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  719. {
  720. client.Connect();
  721. if (client.Exists(remoteFile))
  722. {
  723. client.DeleteFile(remoteFile);
  724. }
  725. try
  726. {
  727. client.AppendAllText(remoteFile, contentToAppend, encoding);
  728. Assert.Fail();
  729. }
  730. catch (SftpPathNotFoundException ex)
  731. {
  732. Assert.IsNull(ex.InnerException);
  733. Assert.AreEqual("No such file", ex.Message);
  734. }
  735. finally
  736. {
  737. if (client.Exists(remoteFile))
  738. {
  739. client.DeleteFile(remoteFile);
  740. }
  741. }
  742. }
  743. }
  744. [TestMethod]
  745. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  746. {
  747. const string contentToAppend = "Forever&\u0116ver";
  748. var expectedContent = contentToAppend;
  749. var encoding = GetRandomEncoding();
  750. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  751. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  752. {
  753. client.Connect();
  754. var remoteFile = GenerateUniqueRemoteFileName();
  755. if (client.Exists(remoteFile))
  756. {
  757. client.DeleteFile(remoteFile);
  758. }
  759. try
  760. {
  761. client.AppendAllText(remoteFile, contentToAppend, encoding);
  762. var text = client.ReadAllText(remoteFile, encoding);
  763. Assert.AreEqual(expectedContent, text);
  764. var actualBytes = client.ReadAllBytes(remoteFile);
  765. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  766. }
  767. finally
  768. {
  769. if (client.Exists(remoteFile))
  770. {
  771. client.DeleteFile(remoteFile);
  772. }
  773. }
  774. }
  775. }
  776. [TestMethod]
  777. public void Sftp_AppendText_Encoding_ExistingFile()
  778. {
  779. const string initialContent = "\u0100ert & Ann";
  780. const string contentToAppend = "Forever&\u0116ver";
  781. var expectedContent = initialContent + contentToAppend;
  782. var encoding = GetRandomEncoding();
  783. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  784. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  785. {
  786. client.Connect();
  787. var remoteFile = GenerateUniqueRemoteFileName();
  788. if (client.Exists(remoteFile))
  789. {
  790. client.DeleteFile(remoteFile);
  791. }
  792. try
  793. {
  794. client.WriteAllText(remoteFile, initialContent, encoding);
  795. using (var sw = client.AppendText(remoteFile, encoding))
  796. {
  797. sw.Write(contentToAppend);
  798. }
  799. var text = client.ReadAllText(remoteFile, encoding);
  800. Assert.AreEqual(expectedContent, text);
  801. var actualBytes = client.ReadAllBytes(remoteFile);
  802. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  803. }
  804. finally
  805. {
  806. if (client.Exists(remoteFile))
  807. {
  808. client.DeleteFile(remoteFile);
  809. }
  810. }
  811. }
  812. }
  813. [TestMethod]
  814. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  815. {
  816. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  817. var encoding = GetRandomEncoding();
  818. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  819. {
  820. client.Connect();
  821. if (client.Exists(remoteFile))
  822. {
  823. client.DeleteFile(remoteFile);
  824. }
  825. StreamWriter sw = null;
  826. try
  827. {
  828. sw = client.AppendText(remoteFile, encoding);
  829. Assert.Fail();
  830. }
  831. catch (SftpPathNotFoundException ex)
  832. {
  833. Assert.IsNull(ex.InnerException);
  834. Assert.AreEqual("No such file", ex.Message);
  835. }
  836. finally
  837. {
  838. sw?.Dispose();
  839. if (client.Exists(remoteFile))
  840. {
  841. client.DeleteFile(remoteFile);
  842. }
  843. }
  844. }
  845. }
  846. [TestMethod]
  847. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  848. {
  849. var encoding = GetRandomEncoding();
  850. const string contentToAppend = "\u0100ert & Ann";
  851. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  852. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  853. {
  854. client.Connect();
  855. var remoteFile = GenerateUniqueRemoteFileName();
  856. if (client.Exists(remoteFile))
  857. {
  858. client.DeleteFile(remoteFile);
  859. }
  860. try
  861. {
  862. using (var sw = client.AppendText(remoteFile, encoding))
  863. {
  864. sw.Write(contentToAppend);
  865. }
  866. var actualBytes = client.ReadAllBytes(remoteFile);
  867. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  868. }
  869. finally
  870. {
  871. if (client.Exists(remoteFile))
  872. {
  873. client.DeleteFile(remoteFile);
  874. }
  875. }
  876. }
  877. }
  878. [TestMethod]
  879. public void Sftp_CreateText_NoEncoding_ExistingFile()
  880. {
  881. var encoding = new UTF8Encoding(false, true);
  882. const string initialContent = "\u0100ert & Ann";
  883. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  884. const string newContent = "\u0116ver";
  885. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  886. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  887. {
  888. client.Connect();
  889. var remoteFile = GenerateUniqueRemoteFileName();
  890. if (client.Exists(remoteFile))
  891. {
  892. client.DeleteFile(remoteFile);
  893. }
  894. try
  895. {
  896. client.WriteAllText(remoteFile, initialContent);
  897. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  898. using (var sw = client.CreateText(remoteFile))
  899. {
  900. sw.Write(newContent);
  901. }
  902. // verify that the file was truncated
  903. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  904. var text = client.ReadAllText(remoteFile);
  905. Assert.AreEqual(newContent, text);
  906. var actualBytes = client.ReadAllBytes(remoteFile);
  907. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  908. }
  909. finally
  910. {
  911. if (client.Exists(remoteFile))
  912. {
  913. client.DeleteFile(remoteFile);
  914. }
  915. }
  916. }
  917. }
  918. [TestMethod]
  919. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  920. {
  921. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  922. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  923. {
  924. client.Connect();
  925. if (client.Exists(remoteFile))
  926. {
  927. client.DeleteFile(remoteFile);
  928. }
  929. StreamWriter sw = null;
  930. try
  931. {
  932. sw = client.CreateText(remoteFile);
  933. Assert.Fail();
  934. }
  935. catch (SftpPathNotFoundException ex)
  936. {
  937. Assert.IsNull(ex.InnerException);
  938. Assert.AreEqual("No such file", ex.Message);
  939. }
  940. finally
  941. {
  942. sw?.Dispose();
  943. if (client.Exists(remoteFile))
  944. {
  945. client.DeleteFile(remoteFile);
  946. }
  947. }
  948. }
  949. }
  950. [TestMethod]
  951. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  952. {
  953. var encoding = new UTF8Encoding(false, true);
  954. var initialContent = "\u0100ert & Ann";
  955. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  956. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  957. {
  958. client.Connect();
  959. var remoteFile = GenerateUniqueRemoteFileName();
  960. if (client.Exists(remoteFile))
  961. {
  962. client.DeleteFile(remoteFile);
  963. }
  964. try
  965. {
  966. using (client.CreateText(remoteFile))
  967. {
  968. }
  969. // verify that empty file was created
  970. Assert.IsTrue(client.Exists(remoteFile));
  971. var file = client.GetAttributes(remoteFile);
  972. Assert.AreEqual(0, file.Size);
  973. client.DeleteFile(remoteFile);
  974. using (var sw = client.CreateText(remoteFile))
  975. {
  976. sw.Write(initialContent);
  977. }
  978. // verify that content is written to file
  979. var text = client.ReadAllText(remoteFile);
  980. Assert.AreEqual(initialContent, text);
  981. var actualBytes = client.ReadAllBytes(remoteFile);
  982. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  983. }
  984. finally
  985. {
  986. if (client.Exists(remoteFile))
  987. {
  988. client.DeleteFile(remoteFile);
  989. }
  990. }
  991. }
  992. }
  993. [TestMethod]
  994. public void Sftp_CreateText_Encoding_ExistingFile()
  995. {
  996. var encoding = GetRandomEncoding();
  997. var initialContent = "\u0100ert & Ann";
  998. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  999. var newContent = "\u0116ver";
  1000. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  1001. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1002. {
  1003. client.Connect();
  1004. var remoteFile = GenerateUniqueRemoteFileName();
  1005. if (client.Exists(remoteFile))
  1006. {
  1007. client.DeleteFile(remoteFile);
  1008. }
  1009. try
  1010. {
  1011. client.WriteAllText(remoteFile, initialContent, encoding);
  1012. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  1013. using (var sw = client.CreateText(remoteFile, encoding))
  1014. {
  1015. sw.Write(newContent);
  1016. }
  1017. // verify that the file was truncated
  1018. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  1019. var text = client.ReadAllText(remoteFile);
  1020. Assert.AreEqual(newContent, text);
  1021. var actualBytes = client.ReadAllBytes(remoteFile);
  1022. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  1023. }
  1024. finally
  1025. {
  1026. if (client.Exists(remoteFile))
  1027. {
  1028. client.DeleteFile(remoteFile);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. [TestMethod]
  1034. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1035. {
  1036. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1037. var encoding = GetRandomEncoding();
  1038. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1039. {
  1040. client.Connect();
  1041. if (client.Exists(remoteFile))
  1042. {
  1043. client.DeleteFile(remoteFile);
  1044. }
  1045. StreamWriter sw = null;
  1046. try
  1047. {
  1048. sw = client.CreateText(remoteFile, encoding);
  1049. Assert.Fail();
  1050. }
  1051. catch (SftpPathNotFoundException ex)
  1052. {
  1053. Assert.IsNull(ex.InnerException);
  1054. Assert.AreEqual("No such file", ex.Message);
  1055. }
  1056. finally
  1057. {
  1058. sw?.Dispose();
  1059. if (client.Exists(remoteFile))
  1060. {
  1061. client.DeleteFile(remoteFile);
  1062. }
  1063. }
  1064. }
  1065. }
  1066. [TestMethod]
  1067. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1068. {
  1069. var encoding = GetRandomEncoding();
  1070. var initialContent = "\u0100ert & Ann";
  1071. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1072. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1073. {
  1074. client.Connect();
  1075. var remoteFile = GenerateUniqueRemoteFileName();
  1076. if (client.Exists(remoteFile))
  1077. {
  1078. client.DeleteFile(remoteFile);
  1079. }
  1080. try
  1081. {
  1082. using (client.CreateText(remoteFile, encoding))
  1083. {
  1084. }
  1085. // verify that file containing only preamble was created
  1086. Assert.IsTrue(client.Exists(remoteFile));
  1087. var file = client.GetAttributes(remoteFile);
  1088. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1089. client.DeleteFile(remoteFile);
  1090. using (var sw = client.CreateText(remoteFile, encoding))
  1091. {
  1092. sw.Write(initialContent);
  1093. }
  1094. // verify that content is written to file
  1095. var text = client.ReadAllText(remoteFile, encoding);
  1096. Assert.AreEqual(initialContent, text);
  1097. var actualBytes = client.ReadAllBytes(remoteFile);
  1098. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  1099. }
  1100. finally
  1101. {
  1102. if (client.Exists(remoteFile))
  1103. {
  1104. client.DeleteFile(remoteFile);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. [TestMethod]
  1110. public void Sftp_DownloadFile_FileDoesNotExist()
  1111. {
  1112. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1113. {
  1114. client.Connect();
  1115. var remoteFile = GenerateUniqueRemoteFileName();
  1116. if (client.Exists(remoteFile))
  1117. {
  1118. client.DeleteFile(remoteFile);
  1119. }
  1120. using (var ms = new MemoryStream())
  1121. {
  1122. try
  1123. {
  1124. client.DownloadFile(remoteFile, ms);
  1125. Assert.Fail();
  1126. }
  1127. catch (SftpPathNotFoundException ex)
  1128. {
  1129. Assert.IsNull(ex.InnerException);
  1130. Assert.AreEqual("No such file", ex.Message);
  1131. // ensure file was not created by us
  1132. Assert.IsFalse(client.Exists(remoteFile));
  1133. }
  1134. finally
  1135. {
  1136. if (client.Exists(remoteFile))
  1137. {
  1138. client.DeleteFile(remoteFile);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. [TestMethod]
  1145. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1146. {
  1147. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1148. {
  1149. client.Connect();
  1150. var remoteFile = GenerateUniqueRemoteFileName();
  1151. if (client.Exists(remoteFile))
  1152. {
  1153. client.DeleteFile(remoteFile);
  1154. }
  1155. try
  1156. {
  1157. client.ReadAllBytes(remoteFile);
  1158. Assert.Fail();
  1159. }
  1160. catch (SftpPathNotFoundException ex)
  1161. {
  1162. Assert.IsNull(ex.InnerException);
  1163. Assert.AreEqual("No such file", ex.Message);
  1164. // ensure file was not created by us
  1165. Assert.IsFalse(client.Exists(remoteFile));
  1166. }
  1167. finally
  1168. {
  1169. if (client.Exists(remoteFile))
  1170. {
  1171. client.DeleteFile(remoteFile);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. [TestMethod]
  1177. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1178. {
  1179. var encoding = new UTF8Encoding(false, true);
  1180. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1181. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1182. encoding);
  1183. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1184. {
  1185. client.Connect();
  1186. var remoteFile = GenerateUniqueRemoteFileName();
  1187. if (client.Exists(remoteFile))
  1188. {
  1189. client.DeleteFile(remoteFile);
  1190. }
  1191. try
  1192. {
  1193. using (var sw = client.AppendText(remoteFile))
  1194. {
  1195. for (var i = 0; i < lines.Length; i++)
  1196. {
  1197. sw.WriteLine(lines[i]);
  1198. }
  1199. }
  1200. var actualLines = client.ReadAllLines(remoteFile);
  1201. Assert.IsNotNull(actualLines);
  1202. CollectionAssert.AreEqual(lines, actualLines);
  1203. var actualBytes = client.ReadAllBytes(remoteFile);
  1204. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1205. }
  1206. finally
  1207. {
  1208. if (client.Exists(remoteFile))
  1209. {
  1210. client.DeleteFile(remoteFile);
  1211. }
  1212. }
  1213. }
  1214. }
  1215. [TestMethod]
  1216. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1217. {
  1218. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1219. {
  1220. client.Connect();
  1221. var remoteFile = GenerateUniqueRemoteFileName();
  1222. if (client.Exists(remoteFile))
  1223. {
  1224. client.DeleteFile(remoteFile);
  1225. }
  1226. try
  1227. {
  1228. client.ReadAllLines(remoteFile);
  1229. Assert.Fail();
  1230. }
  1231. catch (SftpPathNotFoundException ex)
  1232. {
  1233. Assert.IsNull(ex.InnerException);
  1234. Assert.AreEqual("No such file", ex.Message);
  1235. // ensure file was not created by us
  1236. Assert.IsFalse(client.Exists(remoteFile));
  1237. }
  1238. finally
  1239. {
  1240. if (client.Exists(remoteFile))
  1241. {
  1242. client.DeleteFile(remoteFile);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. [TestMethod]
  1248. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1249. {
  1250. var encoding = GetRandomEncoding();
  1251. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1252. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1253. encoding);
  1254. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1255. {
  1256. client.Connect();
  1257. var remoteFile = GenerateUniqueRemoteFileName();
  1258. if (client.Exists(remoteFile))
  1259. {
  1260. client.DeleteFile(remoteFile);
  1261. }
  1262. try
  1263. {
  1264. using (var sw = client.AppendText(remoteFile, encoding))
  1265. {
  1266. for (var i = 0; i < lines.Length; i++)
  1267. {
  1268. sw.WriteLine(lines[i]);
  1269. }
  1270. }
  1271. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1272. Assert.IsNotNull(actualLines);
  1273. CollectionAssert.AreEqual(lines, actualLines);
  1274. var actualBytes = client.ReadAllBytes(remoteFile);
  1275. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1276. }
  1277. finally
  1278. {
  1279. if (client.Exists(remoteFile))
  1280. {
  1281. client.DeleteFile(remoteFile);
  1282. }
  1283. }
  1284. }
  1285. }
  1286. [TestMethod]
  1287. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1288. {
  1289. var encoding = GetRandomEncoding();
  1290. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1291. {
  1292. client.Connect();
  1293. var remoteFile = GenerateUniqueRemoteFileName();
  1294. if (client.Exists(remoteFile))
  1295. {
  1296. client.DeleteFile(remoteFile);
  1297. }
  1298. try
  1299. {
  1300. client.ReadAllLines(remoteFile, encoding);
  1301. Assert.Fail();
  1302. }
  1303. catch (SftpPathNotFoundException ex)
  1304. {
  1305. Assert.IsNull(ex.InnerException);
  1306. Assert.AreEqual("No such file", ex.Message);
  1307. // ensure file was not created by us
  1308. Assert.IsFalse(client.Exists(remoteFile));
  1309. }
  1310. finally
  1311. {
  1312. if (client.Exists(remoteFile))
  1313. {
  1314. client.DeleteFile(remoteFile);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. [TestMethod]
  1320. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1321. {
  1322. var encoding = new UTF8Encoding(false, true);
  1323. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1324. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1325. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1326. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1327. {
  1328. client.Connect();
  1329. var remoteFile = GenerateUniqueRemoteFileName();
  1330. if (client.Exists(remoteFile))
  1331. {
  1332. client.DeleteFile(remoteFile);
  1333. }
  1334. try
  1335. {
  1336. using (var sw = client.AppendText(remoteFile))
  1337. {
  1338. for (var i = 0; i < lines.Length; i++)
  1339. {
  1340. sw.WriteLine(lines[i]);
  1341. }
  1342. }
  1343. var actualText = client.ReadAllText(remoteFile);
  1344. Assert.AreEqual(expectedText, actualText);
  1345. var actualBytes = client.ReadAllBytes(remoteFile);
  1346. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1347. }
  1348. finally
  1349. {
  1350. if (client.Exists(remoteFile))
  1351. {
  1352. client.DeleteFile(remoteFile);
  1353. }
  1354. }
  1355. }
  1356. }
  1357. [TestMethod]
  1358. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1359. {
  1360. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1361. {
  1362. client.Connect();
  1363. var remoteFile = GenerateUniqueRemoteFileName();
  1364. if (client.Exists(remoteFile))
  1365. {
  1366. client.DeleteFile(remoteFile);
  1367. }
  1368. try
  1369. {
  1370. client.ReadAllText(remoteFile);
  1371. Assert.Fail();
  1372. }
  1373. catch (SftpPathNotFoundException ex)
  1374. {
  1375. Assert.IsNull(ex.InnerException);
  1376. Assert.AreEqual("No such file", ex.Message);
  1377. // ensure file was not created by us
  1378. Assert.IsFalse(client.Exists(remoteFile));
  1379. }
  1380. finally
  1381. {
  1382. if (client.Exists(remoteFile))
  1383. {
  1384. client.DeleteFile(remoteFile);
  1385. }
  1386. }
  1387. }
  1388. }
  1389. [TestMethod]
  1390. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1391. {
  1392. var encoding = GetRandomEncoding();
  1393. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1394. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1395. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1396. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1397. {
  1398. client.Connect();
  1399. var remoteFile = GenerateUniqueRemoteFileName();
  1400. if (client.Exists(remoteFile))
  1401. {
  1402. client.DeleteFile(remoteFile);
  1403. }
  1404. try
  1405. {
  1406. using (var sw = client.AppendText(remoteFile, encoding))
  1407. {
  1408. for (var i = 0; i < lines.Length; i++)
  1409. {
  1410. sw.WriteLine(lines[i]);
  1411. }
  1412. }
  1413. var actualText = client.ReadAllText(remoteFile, encoding);
  1414. Assert.AreEqual(expectedText, actualText);
  1415. var actualBytes = client.ReadAllBytes(remoteFile);
  1416. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1417. }
  1418. finally
  1419. {
  1420. if (client.Exists(remoteFile))
  1421. {
  1422. client.DeleteFile(remoteFile);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. [TestMethod]
  1428. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1429. {
  1430. var encoding = GetRandomEncoding();
  1431. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1432. {
  1433. client.Connect();
  1434. var remoteFile = GenerateUniqueRemoteFileName();
  1435. if (client.Exists(remoteFile))
  1436. {
  1437. client.DeleteFile(remoteFile);
  1438. }
  1439. try
  1440. {
  1441. client.ReadAllText(remoteFile, encoding);
  1442. Assert.Fail();
  1443. }
  1444. catch (SftpPathNotFoundException ex)
  1445. {
  1446. Assert.IsNull(ex.InnerException);
  1447. Assert.AreEqual("No such file", ex.Message);
  1448. // ensure file was not created by us
  1449. Assert.IsFalse(client.Exists(remoteFile));
  1450. }
  1451. finally
  1452. {
  1453. if (client.Exists(remoteFile))
  1454. {
  1455. client.DeleteFile(remoteFile);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. [TestMethod]
  1461. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1462. {
  1463. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1464. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1465. {
  1466. client.Connect();
  1467. var remoteFile = GenerateUniqueRemoteFileName();
  1468. if (client.Exists(remoteFile))
  1469. {
  1470. client.DeleteFile(remoteFile);
  1471. }
  1472. try
  1473. {
  1474. using (var sw = client.AppendText(remoteFile))
  1475. {
  1476. for (var i = 0; i < lines.Length; i++)
  1477. {
  1478. sw.WriteLine(lines[i]);
  1479. }
  1480. }
  1481. var actualLines = client.ReadLines(remoteFile);
  1482. Assert.IsNotNull(actualLines);
  1483. // These two lines together test double enumeration.
  1484. Assert.AreEqual(lines[0], actualLines.First());
  1485. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1486. }
  1487. finally
  1488. {
  1489. if (client.Exists(remoteFile))
  1490. {
  1491. client.DeleteFile(remoteFile);
  1492. }
  1493. }
  1494. }
  1495. }
  1496. [TestMethod]
  1497. [DataRow(false)]
  1498. [DataRow(true)]
  1499. public void Sftp_ReadLines_FileDoesNotExist(bool encoding)
  1500. {
  1501. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1502. {
  1503. client.Connect();
  1504. var remoteFile = GenerateUniqueRemoteFileName();
  1505. if (client.Exists(remoteFile))
  1506. {
  1507. client.DeleteFile(remoteFile);
  1508. }
  1509. // This exception should bubble up immediately
  1510. var nullEx = encoding
  1511. ? Assert.Throws<ArgumentNullException>(() => client.ReadLines(null, GetRandomEncoding()))
  1512. : Assert.Throws<ArgumentNullException>(() => client.ReadLines(null));
  1513. Assert.AreEqual("path", nullEx.ParamName);
  1514. try
  1515. {
  1516. var ex = Assert.ThrowsExactly<SftpPathNotFoundException>(() =>
  1517. {
  1518. // The PathNotFound exception is permitted to bubble up only upon
  1519. // enumerating.
  1520. var lines = encoding
  1521. ? client.ReadLines(remoteFile, GetRandomEncoding())
  1522. : client.ReadLines(remoteFile);
  1523. using var enumerator = lines.GetEnumerator();
  1524. _ = enumerator.MoveNext();
  1525. });
  1526. Assert.IsNull(ex.InnerException);
  1527. Assert.AreEqual("No such file", ex.Message);
  1528. // ensure file was not created by us
  1529. Assert.IsFalse(client.Exists(remoteFile));
  1530. }
  1531. finally
  1532. {
  1533. if (client.Exists(remoteFile))
  1534. {
  1535. client.DeleteFile(remoteFile);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. [TestMethod]
  1541. public void Sftp_ReadLines_Encoding_ExistingFile()
  1542. {
  1543. var encoding = GetRandomEncoding();
  1544. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1545. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1546. {
  1547. client.Connect();
  1548. var remoteFile = GenerateUniqueRemoteFileName();
  1549. if (client.Exists(remoteFile))
  1550. {
  1551. client.DeleteFile(remoteFile);
  1552. }
  1553. try
  1554. {
  1555. using (var sw = client.AppendText(remoteFile, encoding))
  1556. {
  1557. for (var i = 0; i < lines.Length; i++)
  1558. {
  1559. sw.WriteLine(lines[i]);
  1560. }
  1561. }
  1562. var actualLines = client.ReadLines(remoteFile, encoding);
  1563. Assert.IsNotNull(actualLines);
  1564. // These two lines together test double enumeration.
  1565. Assert.AreEqual(lines[0], actualLines.First());
  1566. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1567. }
  1568. finally
  1569. {
  1570. if (client.Exists(remoteFile))
  1571. {
  1572. client.DeleteFile(remoteFile);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. [TestMethod]
  1578. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1579. {
  1580. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1581. var content = GenerateRandom(size: 5);
  1582. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1583. {
  1584. client.Connect();
  1585. if (client.Exists(remoteFile))
  1586. {
  1587. client.DeleteFile(remoteFile);
  1588. }
  1589. try
  1590. {
  1591. client.WriteAllBytes(remoteFile, content);
  1592. Assert.Fail();
  1593. }
  1594. catch (SftpPathNotFoundException ex)
  1595. {
  1596. Assert.IsNull(ex.InnerException);
  1597. Assert.AreEqual("No such file", ex.Message);
  1598. }
  1599. finally
  1600. {
  1601. if (client.Exists(remoteFile))
  1602. {
  1603. client.DeleteFile(remoteFile);
  1604. }
  1605. }
  1606. }
  1607. }
  1608. [TestMethod]
  1609. public void Sftp_WriteAllBytes_ExistingFile()
  1610. {
  1611. var initialContent = GenerateRandom(size: 13);
  1612. var newContent1 = GenerateRandom(size: 5);
  1613. var newContent2 = GenerateRandom(size: 50000);
  1614. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1615. {
  1616. client.Connect();
  1617. var remoteFile = GenerateUniqueRemoteFileName();
  1618. if (client.Exists(remoteFile))
  1619. {
  1620. client.DeleteFile(remoteFile);
  1621. }
  1622. try
  1623. {
  1624. using (var fs = client.Create(remoteFile))
  1625. {
  1626. fs.Write(initialContent, offset: 0, initialContent.Length);
  1627. }
  1628. #region Write less bytes than the current content, overwriting that content
  1629. client.WriteAllBytes(remoteFile, newContent1);
  1630. var actualContent1 = client.ReadAllBytes(remoteFile);
  1631. CollectionAssert.AreEqual(newContent1, actualContent1);
  1632. #endregion
  1633. #region Write more bytes than the current content, overwriting and appending to that content
  1634. client.WriteAllBytes(remoteFile, newContent2);
  1635. var actualContent2 = client.ReadAllBytes(remoteFile);
  1636. CollectionAssert.AreEqual(newContent2, actualContent2);
  1637. #endregion
  1638. }
  1639. finally
  1640. {
  1641. if (client.Exists(remoteFile))
  1642. {
  1643. client.DeleteFile(remoteFile);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. [TestMethod]
  1649. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1650. {
  1651. var content = GenerateRandom(size: 13);
  1652. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1653. {
  1654. client.Connect();
  1655. var remoteFile = GenerateUniqueRemoteFileName();
  1656. if (client.Exists(remoteFile))
  1657. {
  1658. client.DeleteFile(remoteFile);
  1659. }
  1660. try
  1661. {
  1662. client.WriteAllBytes(remoteFile, content);
  1663. var actualContent1 = client.ReadAllBytes(remoteFile);
  1664. CollectionAssert.AreEqual(content, actualContent1);
  1665. }
  1666. finally
  1667. {
  1668. if (client.Exists(remoteFile))
  1669. {
  1670. client.DeleteFile(remoteFile);
  1671. }
  1672. }
  1673. }
  1674. }
  1675. [TestMethod]
  1676. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1677. {
  1678. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1679. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1680. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1681. {
  1682. client.Connect();
  1683. if (client.Exists(remoteFile))
  1684. {
  1685. client.DeleteFile(remoteFile);
  1686. }
  1687. try
  1688. {
  1689. client.WriteAllLines(remoteFile, linesToWrite);
  1690. Assert.Fail();
  1691. }
  1692. catch (SftpPathNotFoundException ex)
  1693. {
  1694. Assert.IsNull(ex.InnerException);
  1695. Assert.AreEqual("No such file", ex.Message);
  1696. }
  1697. finally
  1698. {
  1699. if (client.Exists(remoteFile))
  1700. {
  1701. client.DeleteFile(remoteFile);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. [TestMethod]
  1707. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1708. {
  1709. var encoding = new UTF8Encoding(false, true);
  1710. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1711. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1712. var linesToWrite1Bytes =
  1713. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1714. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1715. var linesToWrite2Bytes =
  1716. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1717. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1718. {
  1719. client.Connect();
  1720. var remoteFile = GenerateUniqueRemoteFileName();
  1721. if (client.Exists(remoteFile))
  1722. {
  1723. client.DeleteFile(remoteFile);
  1724. }
  1725. try
  1726. {
  1727. // create initial content
  1728. client.WriteAllText(remoteFile, initialContent);
  1729. #region Write less bytes than the current content, overwriting that content
  1730. client.WriteAllLines(remoteFile, linesToWrite1);
  1731. var actualBytes = client.ReadAllBytes(remoteFile);
  1732. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1733. #endregion
  1734. #region Write more bytes than the current content, overwriting and appending to that content
  1735. client.WriteAllLines(remoteFile, linesToWrite2);
  1736. actualBytes = client.ReadAllBytes(remoteFile);
  1737. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1738. #endregion Write more bytes than the current content, overwriting and appending to that content
  1739. }
  1740. finally
  1741. {
  1742. if (client.Exists(remoteFile))
  1743. {
  1744. client.DeleteFile(remoteFile);
  1745. }
  1746. }
  1747. }
  1748. }
  1749. [TestMethod]
  1750. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1751. {
  1752. var encoding = new UTF8Encoding(false, true);
  1753. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1754. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1755. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1756. {
  1757. client.Connect();
  1758. var remoteFile = GenerateUniqueRemoteFileName();
  1759. if (client.Exists(remoteFile))
  1760. {
  1761. client.DeleteFile(remoteFile);
  1762. }
  1763. try
  1764. {
  1765. client.WriteAllLines(remoteFile, linesToWrite);
  1766. var actualBytes = client.ReadAllBytes(remoteFile);
  1767. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1768. }
  1769. finally
  1770. {
  1771. if (client.Exists(remoteFile))
  1772. {
  1773. client.DeleteFile(remoteFile);
  1774. }
  1775. }
  1776. }
  1777. }
  1778. [TestMethod]
  1779. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1780. {
  1781. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1782. var encoding = GetRandomEncoding();
  1783. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1784. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1785. {
  1786. client.Connect();
  1787. if (client.Exists(remoteFile))
  1788. {
  1789. client.DeleteFile(remoteFile);
  1790. }
  1791. try
  1792. {
  1793. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1794. Assert.Fail();
  1795. }
  1796. catch (SftpPathNotFoundException ex)
  1797. {
  1798. Assert.IsNull(ex.InnerException);
  1799. Assert.AreEqual("No such file", ex.Message);
  1800. }
  1801. finally
  1802. {
  1803. if (client.Exists(remoteFile))
  1804. {
  1805. client.DeleteFile(remoteFile);
  1806. }
  1807. }
  1808. }
  1809. }
  1810. [TestMethod]
  1811. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1812. {
  1813. var encoding = GetRandomEncoding();
  1814. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1815. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1816. var linesToWrite1Bytes =
  1817. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1818. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1819. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1820. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1821. {
  1822. client.Connect();
  1823. var remoteFile = GenerateUniqueRemoteFileName();
  1824. if (client.Exists(remoteFile))
  1825. {
  1826. client.DeleteFile(remoteFile);
  1827. }
  1828. try
  1829. {
  1830. // create initial content
  1831. client.WriteAllText(remoteFile, initialContent, encoding);
  1832. #region Write less bytes than the current content, overwriting that content
  1833. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  1834. var actualBytes = client.ReadAllBytes(remoteFile);
  1835. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1836. #endregion
  1837. #region Write more bytes than the current content, overwriting and appending to that content
  1838. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  1839. actualBytes = client.ReadAllBytes(remoteFile);
  1840. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1841. #endregion Write more bytes than the current content, overwriting and appending to that content
  1842. }
  1843. finally
  1844. {
  1845. if (client.Exists(remoteFile))
  1846. {
  1847. client.DeleteFile(remoteFile);
  1848. }
  1849. }
  1850. }
  1851. }
  1852. [TestMethod]
  1853. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  1854. {
  1855. var encoding = GetRandomEncoding();
  1856. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1857. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1858. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1859. {
  1860. client.Connect();
  1861. var remoteFile = GenerateUniqueRemoteFileName();
  1862. if (client.Exists(remoteFile))
  1863. {
  1864. client.DeleteFile(remoteFile);
  1865. }
  1866. try
  1867. {
  1868. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1869. var actualBytes = client.ReadAllBytes(remoteFile);
  1870. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1871. }
  1872. finally
  1873. {
  1874. if (client.Exists(remoteFile))
  1875. {
  1876. client.DeleteFile(remoteFile);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. [TestMethod]
  1882. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  1883. {
  1884. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1885. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1886. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1887. {
  1888. client.Connect();
  1889. if (client.Exists(remoteFile))
  1890. {
  1891. client.DeleteFile(remoteFile);
  1892. }
  1893. try
  1894. {
  1895. client.WriteAllLines(remoteFile, linesToWrite);
  1896. Assert.Fail();
  1897. }
  1898. catch (SftpPathNotFoundException ex)
  1899. {
  1900. Assert.IsNull(ex.InnerException);
  1901. Assert.AreEqual("No such file", ex.Message);
  1902. }
  1903. finally
  1904. {
  1905. if (client.Exists(remoteFile))
  1906. {
  1907. client.DeleteFile(remoteFile);
  1908. }
  1909. }
  1910. }
  1911. }
  1912. [TestMethod]
  1913. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  1914. {
  1915. var encoding = new UTF8Encoding(false, true);
  1916. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1917. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1918. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1919. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1920. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1921. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1922. {
  1923. client.Connect();
  1924. var remoteFile = GenerateUniqueRemoteFileName();
  1925. if (client.Exists(remoteFile))
  1926. {
  1927. client.DeleteFile(remoteFile);
  1928. }
  1929. try
  1930. {
  1931. // create initial content
  1932. client.WriteAllText(remoteFile, initialContent);
  1933. #region Write less bytes than the current content, overwriting that content
  1934. client.WriteAllLines(remoteFile, linesToWrite1);
  1935. var actualBytes = client.ReadAllBytes(remoteFile);
  1936. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1937. #endregion
  1938. #region Write more bytes than the current content, overwriting and appending to that content
  1939. client.WriteAllLines(remoteFile, linesToWrite2);
  1940. actualBytes = client.ReadAllBytes(remoteFile);
  1941. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1942. #endregion Write more bytes than the current content, overwriting and appending to that content
  1943. }
  1944. finally
  1945. {
  1946. if (client.Exists(remoteFile))
  1947. {
  1948. client.DeleteFile(remoteFile);
  1949. }
  1950. }
  1951. }
  1952. }
  1953. [TestMethod]
  1954. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  1955. {
  1956. var encoding = new UTF8Encoding(false, true);
  1957. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1958. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1959. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1960. {
  1961. client.Connect();
  1962. var remoteFile = GenerateUniqueRemoteFileName();
  1963. if (client.Exists(remoteFile))
  1964. {
  1965. client.DeleteFile(remoteFile);
  1966. }
  1967. try
  1968. {
  1969. client.WriteAllLines(remoteFile, linesToWrite);
  1970. var actualBytes = client.ReadAllBytes(remoteFile);
  1971. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1972. }
  1973. finally
  1974. {
  1975. if (client.Exists(remoteFile))
  1976. {
  1977. client.DeleteFile(remoteFile);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. [TestMethod]
  1983. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  1984. {
  1985. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1986. var encoding = GetRandomEncoding();
  1987. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1988. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1989. {
  1990. client.Connect();
  1991. if (client.Exists(remoteFile))
  1992. {
  1993. client.DeleteFile(remoteFile);
  1994. }
  1995. try
  1996. {
  1997. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1998. Assert.Fail();
  1999. }
  2000. catch (SftpPathNotFoundException ex)
  2001. {
  2002. Assert.IsNull(ex.InnerException);
  2003. Assert.AreEqual("No such file", ex.Message);
  2004. }
  2005. finally
  2006. {
  2007. if (client.Exists(remoteFile))
  2008. {
  2009. client.DeleteFile(remoteFile);
  2010. }
  2011. }
  2012. }
  2013. }
  2014. [TestMethod]
  2015. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2016. {
  2017. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2018. var encoding = GetRandomEncoding();
  2019. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2020. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2021. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2022. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2023. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2024. {
  2025. client.Connect();
  2026. var remoteFile = GenerateUniqueRemoteFileName();
  2027. if (client.Exists(remoteFile))
  2028. {
  2029. client.DeleteFile(remoteFile);
  2030. }
  2031. try
  2032. {
  2033. // create initial content
  2034. client.WriteAllText(remoteFile, initialContent, encoding);
  2035. #region Write less bytes than the current content, overwriting that content
  2036. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2037. var actualBytes = client.ReadAllBytes(remoteFile);
  2038. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  2039. #endregion
  2040. #region Write more bytes than the current content, overwriting and appending to that content
  2041. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2042. actualBytes = client.ReadAllBytes(remoteFile);
  2043. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  2044. #endregion
  2045. }
  2046. finally
  2047. {
  2048. if (client.Exists(remoteFile))
  2049. {
  2050. client.DeleteFile(remoteFile);
  2051. }
  2052. }
  2053. }
  2054. }
  2055. [TestMethod]
  2056. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2057. {
  2058. var encoding = GetRandomEncoding();
  2059. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2060. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2061. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2062. {
  2063. client.Connect();
  2064. var remoteFile = GenerateUniqueRemoteFileName();
  2065. if (client.Exists(remoteFile))
  2066. {
  2067. client.DeleteFile(remoteFile);
  2068. }
  2069. try
  2070. {
  2071. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2072. var actualBytes = client.ReadAllBytes(remoteFile);
  2073. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  2074. }
  2075. finally
  2076. {
  2077. if (client.Exists(remoteFile))
  2078. {
  2079. client.DeleteFile(remoteFile);
  2080. }
  2081. }
  2082. }
  2083. }
  2084. [TestMethod]
  2085. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2086. {
  2087. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2088. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2089. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2090. {
  2091. client.Connect();
  2092. if (client.Exists(remoteFile))
  2093. {
  2094. client.DeleteFile(remoteFile);
  2095. }
  2096. try
  2097. {
  2098. client.WriteAllText(remoteFile, initialContent);
  2099. Assert.Fail();
  2100. }
  2101. catch (SftpPathNotFoundException ex)
  2102. {
  2103. Assert.IsNull(ex.InnerException);
  2104. Assert.AreEqual("No such file", ex.Message);
  2105. }
  2106. finally
  2107. {
  2108. if (client.Exists(remoteFile))
  2109. {
  2110. client.DeleteFile(remoteFile);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. [TestMethod]
  2116. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2117. {
  2118. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2119. const string newContent1 = "For\u0116ver & Ever";
  2120. var encoding = new UTF8Encoding(false, true);
  2121. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2122. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2123. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2124. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2125. {
  2126. client.Connect();
  2127. var remoteFile = GenerateUniqueRemoteFileName();
  2128. if (client.Exists(remoteFile))
  2129. {
  2130. client.DeleteFile(remoteFile);
  2131. }
  2132. try
  2133. {
  2134. client.WriteAllText(remoteFile, initialContent);
  2135. #region Write less bytes than the current content, overwriting that content
  2136. client.WriteAllText(remoteFile, newContent1);
  2137. var actualBytes = client.ReadAllBytes(remoteFile);
  2138. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2139. #endregion
  2140. #region Write more bytes than the current content, overwriting and appending to that content
  2141. client.WriteAllText(remoteFile, newContent2);
  2142. actualBytes = client.ReadAllBytes(remoteFile);
  2143. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2144. #endregion Write more bytes than the current content, overwriting and appending to that content
  2145. }
  2146. finally
  2147. {
  2148. if (client.Exists(remoteFile))
  2149. {
  2150. client.DeleteFile(remoteFile);
  2151. }
  2152. }
  2153. }
  2154. }
  2155. [TestMethod]
  2156. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2157. {
  2158. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2159. var encoding = new UTF8Encoding(false, true);
  2160. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2162. {
  2163. client.Connect();
  2164. var remoteFile = GenerateUniqueRemoteFileName();
  2165. if (client.Exists(remoteFile))
  2166. {
  2167. client.DeleteFile(remoteFile);
  2168. }
  2169. try
  2170. {
  2171. client.WriteAllText(remoteFile, initialContent);
  2172. var actualBytes = client.ReadAllBytes(remoteFile);
  2173. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2174. }
  2175. finally
  2176. {
  2177. if (client.Exists(remoteFile))
  2178. {
  2179. client.DeleteFile(remoteFile);
  2180. }
  2181. }
  2182. }
  2183. }
  2184. [TestMethod]
  2185. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2186. {
  2187. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2188. var encoding = GetRandomEncoding();
  2189. const string content = "For\u0116ver & Ever";
  2190. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2191. {
  2192. client.Connect();
  2193. if (client.Exists(remoteFile))
  2194. {
  2195. client.DeleteFile(remoteFile);
  2196. }
  2197. try
  2198. {
  2199. client.WriteAllText(remoteFile, content, encoding);
  2200. Assert.Fail();
  2201. }
  2202. catch (SftpPathNotFoundException ex)
  2203. {
  2204. Assert.IsNull(ex.InnerException);
  2205. Assert.AreEqual("No such file", ex.Message);
  2206. }
  2207. finally
  2208. {
  2209. if (client.Exists(remoteFile))
  2210. {
  2211. client.DeleteFile(remoteFile);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. [TestMethod]
  2217. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2218. {
  2219. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2220. const string newContent1 = "For\u0116ver & Ever";
  2221. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2222. var encoding = GetRandomEncoding();
  2223. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2224. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2225. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2226. {
  2227. client.Connect();
  2228. var remoteFile = GenerateUniqueRemoteFileName();
  2229. if (client.Exists(remoteFile))
  2230. {
  2231. client.DeleteFile(remoteFile);
  2232. }
  2233. try
  2234. {
  2235. client.WriteAllText(remoteFile, initialContent, encoding);
  2236. #region Write less bytes than the current content, overwriting that content
  2237. client.WriteAllText(remoteFile, newContent1, encoding);
  2238. var actualBytes = client.ReadAllBytes(remoteFile);
  2239. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2240. #endregion
  2241. #region Write more bytes than the current content, overwriting and appending to that content
  2242. client.WriteAllText(remoteFile, newContent2, encoding);
  2243. actualBytes = client.ReadAllBytes(remoteFile);
  2244. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2245. #endregion Write more bytes than the current content, overwriting and appending to that content
  2246. }
  2247. finally
  2248. {
  2249. if (client.Exists(remoteFile))
  2250. {
  2251. client.DeleteFile(remoteFile);
  2252. }
  2253. }
  2254. }
  2255. }
  2256. [TestMethod]
  2257. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2258. {
  2259. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2260. var encoding = GetRandomEncoding();
  2261. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2262. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2263. {
  2264. client.Connect();
  2265. var remoteFile = GenerateUniqueRemoteFileName();
  2266. if (client.Exists(remoteFile))
  2267. {
  2268. client.DeleteFile(remoteFile);
  2269. }
  2270. try
  2271. {
  2272. client.WriteAllText(remoteFile, initialContent, encoding);
  2273. var actualBytes = client.ReadAllBytes(remoteFile);
  2274. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2275. }
  2276. finally
  2277. {
  2278. if (client.Exists(remoteFile))
  2279. {
  2280. client.DeleteFile(remoteFile);
  2281. }
  2282. }
  2283. }
  2284. }
  2285. [TestMethod]
  2286. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2287. {
  2288. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2289. {
  2290. client.Connect();
  2291. var remoteFile = GenerateUniqueRemoteFileName();
  2292. if (client.Exists(remoteFile))
  2293. {
  2294. client.DeleteFile(remoteFile);
  2295. }
  2296. try
  2297. {
  2298. using (var ms = new MemoryStream())
  2299. {
  2300. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2301. try
  2302. {
  2303. client.EndDownloadFile(asyncResult);
  2304. Assert.Fail();
  2305. }
  2306. catch (SftpPathNotFoundException ex)
  2307. {
  2308. Assert.IsNull(ex.InnerException);
  2309. Assert.AreEqual("No such file", ex.Message);
  2310. // ensure file was not created by us
  2311. Assert.IsFalse(client.Exists(remoteFile));
  2312. }
  2313. }
  2314. }
  2315. finally
  2316. {
  2317. if (client.Exists(remoteFile))
  2318. {
  2319. client.DeleteFile(remoteFile);
  2320. }
  2321. }
  2322. }
  2323. }
  2324. [TestMethod]
  2325. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2326. {
  2327. const string remoteDirectory = "/home/sshnet/test123";
  2328. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2329. {
  2330. client.Connect();
  2331. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2332. {
  2333. command.Execute();
  2334. }
  2335. }
  2336. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2337. {
  2338. client.Connect();
  2339. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2340. try
  2341. {
  2342. client.EndListDirectory(asyncResult);
  2343. Assert.Fail();
  2344. }
  2345. catch (SftpPathNotFoundException ex)
  2346. {
  2347. Assert.IsNull(ex.InnerException);
  2348. Assert.AreEqual("No such file", ex.Message);
  2349. // ensure directory was not created by us
  2350. Assert.IsFalse(client.Exists(remoteDirectory));
  2351. }
  2352. }
  2353. }
  2354. [TestMethod]
  2355. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2356. {
  2357. const int size = 50 * 1024 * 1024;
  2358. const string remoteDirectory = "/home/sshnet/test123";
  2359. const string remoteFile = remoteDirectory + "/test";
  2360. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2361. {
  2362. client.Connect();
  2363. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2364. {
  2365. command.Execute();
  2366. }
  2367. }
  2368. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2369. {
  2370. client.Connect();
  2371. var memoryStream = CreateMemoryStream(size);
  2372. memoryStream.Position = 0;
  2373. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2374. try
  2375. {
  2376. client.EndUploadFile(asyncResult);
  2377. Assert.Fail();
  2378. }
  2379. catch (SftpPathNotFoundException)
  2380. {
  2381. }
  2382. }
  2383. }
  2384. [TestMethod]
  2385. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2386. {
  2387. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2388. {
  2389. client.Connect();
  2390. var remoteFile = GenerateUniqueRemoteFileName();
  2391. if (client.Exists(remoteFile))
  2392. {
  2393. client.DeleteFile(remoteFile);
  2394. }
  2395. try
  2396. {
  2397. var uploadMemoryStream = new MemoryStream();
  2398. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2399. sw.Write("Gert & Ann");
  2400. sw.Flush();
  2401. uploadMemoryStream.Position = 0;
  2402. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2403. client.EndUploadFile(asyncResult);
  2404. using (var downloadMemoryStream = new MemoryStream())
  2405. {
  2406. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2407. downloadMemoryStream.Position = 0;
  2408. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2409. {
  2410. var content = sr.ReadToEnd();
  2411. Assert.AreEqual("Gert & Ann", content);
  2412. }
  2413. }
  2414. }
  2415. finally
  2416. {
  2417. if (client.Exists(remoteFile))
  2418. {
  2419. client.DeleteFile(remoteFile);
  2420. }
  2421. }
  2422. }
  2423. }
  2424. [TestMethod]
  2425. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2426. {
  2427. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2428. {
  2429. client.Connect();
  2430. var remoteFile = GenerateUniqueRemoteFileName();
  2431. if (client.Exists(remoteFile))
  2432. {
  2433. client.DeleteFile(remoteFile);
  2434. }
  2435. try
  2436. {
  2437. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2438. var uploadMemoryStream = new MemoryStream();
  2439. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2440. sw.Write("Ann & Gert");
  2441. sw.Flush();
  2442. uploadMemoryStream.Position = 0;
  2443. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2444. client.EndUploadFile(asyncResult);
  2445. using (var downloadMemoryStream = new MemoryStream())
  2446. {
  2447. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2448. downloadMemoryStream.Position = 0;
  2449. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2450. {
  2451. var content = sr.ReadToEnd();
  2452. Assert.AreEqual("Ann & Gert", content);
  2453. }
  2454. }
  2455. }
  2456. finally
  2457. {
  2458. if (client.Exists(remoteFile))
  2459. {
  2460. client.DeleteFile(remoteFile);
  2461. }
  2462. }
  2463. }
  2464. }
  2465. [TestMethod]
  2466. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2467. {
  2468. const int size = 50 * 1024 * 1024;
  2469. const string remoteDirectory = "/home/sshnet/test123";
  2470. const string remoteFile = remoteDirectory + "/test";
  2471. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2472. {
  2473. client.Connect();
  2474. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2475. {
  2476. command.Execute();
  2477. }
  2478. }
  2479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2480. {
  2481. client.Connect();
  2482. var memoryStream = CreateMemoryStream(size);
  2483. memoryStream.Position = 0;
  2484. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2485. try
  2486. {
  2487. client.EndUploadFile(asyncResult);
  2488. Assert.Fail();
  2489. }
  2490. catch (SftpPathNotFoundException)
  2491. {
  2492. }
  2493. }
  2494. }
  2495. [TestMethod]
  2496. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2497. {
  2498. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2499. {
  2500. client.Connect();
  2501. var remoteFile = GenerateUniqueRemoteFileName();
  2502. if (client.Exists(remoteFile))
  2503. {
  2504. client.DeleteFile(remoteFile);
  2505. }
  2506. try
  2507. {
  2508. using (var uploadMemoryStream = new MemoryStream())
  2509. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2510. {
  2511. sw.Write("Gert & Ann");
  2512. sw.Flush();
  2513. uploadMemoryStream.Position = 0;
  2514. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2515. client.EndUploadFile(asyncResult);
  2516. }
  2517. using (var downloadMemoryStream = new MemoryStream())
  2518. {
  2519. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2520. downloadMemoryStream.Position = 0;
  2521. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2522. {
  2523. var content = sr.ReadToEnd();
  2524. Assert.AreEqual("Gert & Ann", content);
  2525. }
  2526. }
  2527. }
  2528. finally
  2529. {
  2530. if (client.Exists(remoteFile))
  2531. {
  2532. client.DeleteFile(remoteFile);
  2533. }
  2534. }
  2535. }
  2536. }
  2537. [TestMethod]
  2538. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2539. {
  2540. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2541. {
  2542. client.Connect();
  2543. var remoteFile = GenerateUniqueRemoteFileName();
  2544. if (client.Exists(remoteFile))
  2545. {
  2546. client.DeleteFile(remoteFile);
  2547. }
  2548. try
  2549. {
  2550. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2551. var uploadMemoryStream = new MemoryStream();
  2552. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2553. sw.Write("Ann & Gert");
  2554. sw.Flush();
  2555. uploadMemoryStream.Position = 0;
  2556. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2557. try
  2558. {
  2559. client.EndUploadFile(asyncResult);
  2560. Assert.Fail();
  2561. }
  2562. catch (SshException ex)
  2563. {
  2564. Assert.AreEqual(typeof(SshException), ex.GetType());
  2565. Assert.IsNull(ex.InnerException);
  2566. Assert.AreEqual("Failure", ex.Message);
  2567. }
  2568. }
  2569. finally
  2570. {
  2571. if (client.Exists(remoteFile))
  2572. {
  2573. client.DeleteFile(remoteFile);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. [TestMethod]
  2579. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2580. {
  2581. const int size = 50 * 1024 * 1024;
  2582. const string remoteDirectory = "/home/sshnet/test123";
  2583. const string remoteFile = remoteDirectory + "/test";
  2584. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2585. {
  2586. client.Connect();
  2587. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2588. {
  2589. command.Execute();
  2590. }
  2591. }
  2592. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2593. {
  2594. client.Connect();
  2595. var memoryStream = CreateMemoryStream(size);
  2596. memoryStream.Position = 0;
  2597. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2598. try
  2599. {
  2600. client.EndUploadFile(asyncResult);
  2601. Assert.Fail();
  2602. }
  2603. catch (SftpPathNotFoundException)
  2604. {
  2605. }
  2606. }
  2607. }
  2608. [TestMethod]
  2609. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2610. {
  2611. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2612. {
  2613. client.Connect();
  2614. var remoteFile = GenerateUniqueRemoteFileName();
  2615. if (client.Exists(remoteFile))
  2616. {
  2617. client.DeleteFile(remoteFile);
  2618. }
  2619. try
  2620. {
  2621. using (var uploadMemoryStream = new MemoryStream())
  2622. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2623. {
  2624. sw.Write("Gert & Ann");
  2625. sw.Flush();
  2626. uploadMemoryStream.Position = 0;
  2627. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2628. client.EndUploadFile(asyncResult);
  2629. }
  2630. using (var downloadMemoryStream = new MemoryStream())
  2631. {
  2632. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2633. downloadMemoryStream.Position = 0;
  2634. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2635. {
  2636. var content = sr.ReadToEnd();
  2637. Assert.AreEqual("Gert & Ann", content);
  2638. }
  2639. }
  2640. }
  2641. finally
  2642. {
  2643. if (client.Exists(remoteFile))
  2644. {
  2645. client.DeleteFile(remoteFile);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. [TestMethod]
  2651. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2652. {
  2653. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2654. {
  2655. client.Connect();
  2656. var remoteFile = GenerateUniqueRemoteFileName();
  2657. if (client.Exists(remoteFile))
  2658. {
  2659. client.DeleteFile(remoteFile);
  2660. }
  2661. try
  2662. {
  2663. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2664. using (var uploadMemoryStream = new MemoryStream())
  2665. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2666. {
  2667. sw.Write("Ann & Gert");
  2668. sw.Flush();
  2669. uploadMemoryStream.Position = 0;
  2670. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2671. client.EndUploadFile(asyncResult);
  2672. }
  2673. using (var downloadMemoryStream = new MemoryStream())
  2674. {
  2675. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2676. downloadMemoryStream.Position = 0;
  2677. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2678. {
  2679. var content = sr.ReadToEnd();
  2680. Assert.AreEqual("Ann & Gert", content);
  2681. }
  2682. }
  2683. }
  2684. finally
  2685. {
  2686. if (client.Exists(remoteFile))
  2687. {
  2688. client.DeleteFile(remoteFile);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. [TestMethod]
  2694. public void Sftp_UploadAndDownloadBigFile()
  2695. {
  2696. const int size = 50 * 1024 * 1024;
  2697. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2698. {
  2699. client.Connect();
  2700. var remoteFile = GenerateUniqueRemoteFileName();
  2701. if (client.Exists(remoteFile))
  2702. {
  2703. client.Delete(remoteFile);
  2704. }
  2705. try
  2706. {
  2707. var memoryStream = CreateMemoryStream(size);
  2708. memoryStream.Position = 0;
  2709. var expectedHash = CreateHash(memoryStream);
  2710. memoryStream.Position = 0;
  2711. client.UploadFile(memoryStream, remoteFile);
  2712. memoryStream.SetLength(0);
  2713. var stopwatch = new Stopwatch();
  2714. stopwatch.Start();
  2715. client.DownloadFile(remoteFile, memoryStream);
  2716. stopwatch.Stop();
  2717. Assert.AreEqual(size, memoryStream.Length);
  2718. memoryStream.Position = 0;
  2719. var actualHash = CreateHash(memoryStream);
  2720. Assert.AreEqual(expectedHash, actualHash);
  2721. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2722. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2723. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2724. }
  2725. finally
  2726. {
  2727. if (client.Exists(remoteFile))
  2728. {
  2729. client.Delete(remoteFile);
  2730. }
  2731. }
  2732. }
  2733. }
  2734. /// <summary>
  2735. /// Issue 1672
  2736. /// </summary>
  2737. [TestMethod]
  2738. public void Sftp_CurrentWorkingDirectory()
  2739. {
  2740. const string homeDirectory = "/home/sshnet";
  2741. const string otherDirectory = homeDirectory + "/dir";
  2742. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2743. {
  2744. client.Connect();
  2745. if (client.Exists(otherDirectory))
  2746. {
  2747. client.DeleteDirectory(otherDirectory);
  2748. }
  2749. try
  2750. {
  2751. client.CreateDirectory(otherDirectory);
  2752. client.ChangeDirectory(otherDirectory);
  2753. using (var s = CreateStreamWithContent("A"))
  2754. {
  2755. client.UploadFile(s, "a.txt");
  2756. }
  2757. using (var s = new MemoryStream())
  2758. {
  2759. client.DownloadFile("a.txt", s);
  2760. s.Position = 0;
  2761. var content = Encoding.ASCII.GetString(s.ToArray());
  2762. Assert.AreEqual("A", content);
  2763. }
  2764. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  2765. client.DeleteFile("a.txt");
  2766. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  2767. client.DeleteDirectory(".");
  2768. Assert.IsFalse(client.Exists(otherDirectory));
  2769. }
  2770. finally
  2771. {
  2772. if (client.Exists(otherDirectory))
  2773. {
  2774. client.DeleteDirectory(otherDirectory);
  2775. }
  2776. }
  2777. }
  2778. }
  2779. [TestMethod]
  2780. public void Sftp_Exists()
  2781. {
  2782. const string remoteHome = "/home/sshnet";
  2783. #region Setup
  2784. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2785. {
  2786. client.Connect();
  2787. #region Clean-up
  2788. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2789. {
  2790. command.Execute();
  2791. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2792. }
  2793. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2794. {
  2795. command.Execute();
  2796. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2797. }
  2798. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2799. )
  2800. {
  2801. command.Execute();
  2802. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2803. }
  2804. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2805. {
  2806. command.Execute();
  2807. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2808. }
  2809. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2810. {
  2811. command.Execute();
  2812. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2813. }
  2814. #endregion Clean-up
  2815. #region Setup
  2816. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2817. {
  2818. command.Execute();
  2819. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2820. }
  2821. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2822. {
  2823. command.Execute();
  2824. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2825. }
  2826. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2827. {
  2828. command.Execute();
  2829. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2830. }
  2831. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2832. {
  2833. command.Execute();
  2834. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2835. }
  2836. #endregion Setup
  2837. }
  2838. #endregion Setup
  2839. #region Assert
  2840. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2841. {
  2842. client.Connect();
  2843. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  2844. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  2845. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  2846. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  2847. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  2848. }
  2849. #endregion Assert
  2850. #region Teardown
  2851. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2852. {
  2853. client.Connect();
  2854. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2855. {
  2856. command.Execute();
  2857. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2858. }
  2859. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2860. {
  2861. command.Execute();
  2862. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2863. }
  2864. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2865. {
  2866. command.Execute();
  2867. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2868. }
  2869. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2870. {
  2871. command.Execute();
  2872. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2873. }
  2874. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2875. {
  2876. command.Execute();
  2877. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2878. }
  2879. }
  2880. #endregion Teardown
  2881. }
  2882. [TestMethod]
  2883. public async Task Sftp_ExistsAsync()
  2884. {
  2885. const string remoteHome = "/home/sshnet";
  2886. #region Setup
  2887. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2888. {
  2889. client.Connect();
  2890. #region Clean-up
  2891. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2892. {
  2893. await command.ExecuteAsync();
  2894. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2895. }
  2896. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2897. {
  2898. await command.ExecuteAsync();
  2899. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2900. }
  2901. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2902. )
  2903. {
  2904. await command.ExecuteAsync();
  2905. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2906. }
  2907. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2908. {
  2909. await command.ExecuteAsync();
  2910. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2911. }
  2912. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2913. {
  2914. await command.ExecuteAsync();
  2915. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2916. }
  2917. #endregion Clean-up
  2918. #region Setup
  2919. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2920. {
  2921. await command.ExecuteAsync();
  2922. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2923. }
  2924. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2925. {
  2926. await command.ExecuteAsync();
  2927. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2928. }
  2929. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2930. {
  2931. await command.ExecuteAsync();
  2932. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2933. }
  2934. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2935. {
  2936. await command.ExecuteAsync();
  2937. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2938. }
  2939. #endregion Setup
  2940. }
  2941. #endregion Setup
  2942. #region Assert
  2943. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2944. {
  2945. await client.ConnectAsync(default).ConfigureAwait(false);
  2946. Assert.IsFalse(await client.ExistsAsync(remoteHome + "/DoesNotExist"));
  2947. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/file.exists"));
  2948. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.file.exists"));
  2949. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/directory.exists"));
  2950. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.directory.exists"));
  2951. }
  2952. #endregion Assert
  2953. #region Teardown
  2954. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2955. {
  2956. client.Connect();
  2957. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2958. {
  2959. await command.ExecuteAsync();
  2960. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2961. }
  2962. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2963. {
  2964. await command.ExecuteAsync();
  2965. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2966. }
  2967. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2968. {
  2969. await command.ExecuteAsync();
  2970. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2971. }
  2972. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2973. {
  2974. await command.ExecuteAsync();
  2975. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2976. }
  2977. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2978. {
  2979. await command.ExecuteAsync();
  2980. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2981. }
  2982. }
  2983. #endregion Teardown
  2984. }
  2985. [TestMethod]
  2986. public void Sftp_ListDirectory()
  2987. {
  2988. const string remoteDirectory = "/home/sshnet/test123";
  2989. try
  2990. {
  2991. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2992. {
  2993. client.Connect();
  2994. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  2995. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  2996. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  2997. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  2998. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  2999. }
  3000. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3001. {
  3002. client.Connect();
  3003. client.ChangeDirectory(remoteDirectory);
  3004. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3005. Assert.AreEqual(5, directoryContent.Count);
  3006. Assert.AreEqual(".", directoryContent[0].Name);
  3007. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3008. Assert.IsTrue(directoryContent[0].IsDirectory);
  3009. Assert.AreEqual("..", directoryContent[1].Name);
  3010. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3011. Assert.IsTrue(directoryContent[1].IsDirectory);
  3012. Assert.AreEqual("file1", directoryContent[2].Name);
  3013. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3014. Assert.IsFalse(directoryContent[2].IsDirectory);
  3015. Assert.AreEqual("file2", directoryContent[3].Name);
  3016. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3017. Assert.IsFalse(directoryContent[3].IsDirectory);
  3018. Assert.AreEqual("sub", directoryContent[4].Name);
  3019. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3020. Assert.IsTrue(directoryContent[4].IsDirectory);
  3021. }
  3022. }
  3023. finally
  3024. {
  3025. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3026. {
  3027. client.Connect();
  3028. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3029. {
  3030. command.Execute();
  3031. }
  3032. }
  3033. }
  3034. }
  3035. [TestMethod]
  3036. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3037. {
  3038. const string remoteDirectory = "/home/sshnet/test123";
  3039. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3040. {
  3041. client.Connect();
  3042. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3043. {
  3044. command.Execute();
  3045. }
  3046. }
  3047. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3048. {
  3049. client.Connect();
  3050. try
  3051. {
  3052. client.ChangeDirectory(remoteDirectory);
  3053. Assert.Fail();
  3054. }
  3055. catch (SftpPathNotFoundException)
  3056. {
  3057. }
  3058. }
  3059. }
  3060. [TestMethod]
  3061. public async Task Sftp_ChangeDirectory_DirectoryDoesNotExistAsync()
  3062. {
  3063. const string remoteDirectory = "/home/sshnet/test123";
  3064. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3065. {
  3066. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3067. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3068. {
  3069. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3070. }
  3071. }
  3072. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3073. {
  3074. client.Connect();
  3075. try
  3076. {
  3077. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3078. Assert.Fail();
  3079. }
  3080. catch (SftpPathNotFoundException)
  3081. {
  3082. }
  3083. }
  3084. }
  3085. [TestMethod]
  3086. public void Sftp_ChangeDirectory_DirectoryExists()
  3087. {
  3088. const string remoteDirectory = "/home/sshnet/test123";
  3089. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3090. {
  3091. client.Connect();
  3092. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3093. {
  3094. command.Execute();
  3095. }
  3096. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3097. {
  3098. command.Execute();
  3099. }
  3100. }
  3101. try
  3102. {
  3103. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3104. {
  3105. client.Connect();
  3106. client.ChangeDirectory(remoteDirectory);
  3107. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3108. using (var uploadStream = CreateMemoryStream(100))
  3109. {
  3110. uploadStream.Position = 0;
  3111. client.UploadFile(uploadStream, "gert.txt");
  3112. uploadStream.Position = 0;
  3113. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3114. {
  3115. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3116. }
  3117. }
  3118. }
  3119. }
  3120. finally
  3121. {
  3122. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3123. {
  3124. client.Connect();
  3125. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3126. {
  3127. command.Execute();
  3128. }
  3129. }
  3130. }
  3131. }
  3132. [TestMethod]
  3133. public async Task Sftp_ChangeDirectory_DirectoryExistsAsync()
  3134. {
  3135. const string remoteDirectory = "/home/sshnet/test123";
  3136. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3137. {
  3138. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3139. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3140. {
  3141. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3142. }
  3143. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3144. {
  3145. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3146. }
  3147. }
  3148. try
  3149. {
  3150. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3151. {
  3152. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3153. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3154. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3155. using (var uploadStream = CreateMemoryStream(100))
  3156. {
  3157. uploadStream.Position = 0;
  3158. await client.UploadFileAsync(uploadStream, "gert.txt").ConfigureAwait(false);
  3159. uploadStream.Position = 0;
  3160. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3161. {
  3162. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3163. }
  3164. }
  3165. }
  3166. }
  3167. finally
  3168. {
  3169. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3170. {
  3171. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3172. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3173. {
  3174. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3175. }
  3176. }
  3177. }
  3178. }
  3179. [TestMethod]
  3180. public void Sftp_SubsystemExecution_Failed()
  3181. {
  3182. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3183. // Disable SFTP subsystem
  3184. remoteSshdConfig.ClearSubsystems()
  3185. .Update()
  3186. .Restart();
  3187. var remoteSshdReconfiguredToDefaultState = false;
  3188. try
  3189. {
  3190. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3191. {
  3192. try
  3193. {
  3194. client.Connect();
  3195. Assert.Fail("Establishing SFTP connection should have failed.");
  3196. }
  3197. catch (SshException ex)
  3198. {
  3199. Assert.IsNull(ex.InnerException);
  3200. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3201. }
  3202. // Re-enable SFTP subsystem
  3203. remoteSshdConfig.Reset();
  3204. remoteSshdReconfiguredToDefaultState = true;
  3205. // ensure we can reconnect the same SftpClient instance
  3206. client.Connect();
  3207. // ensure SFTP session is correctly established
  3208. Assert.IsTrue(client.Exists("."));
  3209. }
  3210. }
  3211. finally
  3212. {
  3213. if (!remoteSshdReconfiguredToDefaultState)
  3214. {
  3215. remoteSshdConfig.Reset();
  3216. }
  3217. }
  3218. }
  3219. [TestMethod]
  3220. public void Sftp_SftpFileStream_ReadAndWrite()
  3221. {
  3222. TestReadAndWrite(
  3223. (s, buffer, offset, count) => s.Read(buffer, offset, count),
  3224. (s, buffer, offset, count) => s.Write(buffer, offset, count));
  3225. }
  3226. [TestMethod]
  3227. public void Sftp_SftpFileStream_ReadAndWriteByte()
  3228. {
  3229. TestReadAndWrite(
  3230. read: (s, buffer, offset, count) =>
  3231. {
  3232. int bytesRead = 0;
  3233. int b;
  3234. while (bytesRead < count && (b = s.ReadByte()) != -1)
  3235. {
  3236. buffer[offset + bytesRead] = (byte)b;
  3237. bytesRead++;
  3238. }
  3239. return bytesRead;
  3240. },
  3241. write: (s, buffer, offset, count) =>
  3242. {
  3243. for (int i = 0; i < count; i++)
  3244. {
  3245. s.WriteByte(buffer[offset + i]);
  3246. }
  3247. });
  3248. }
  3249. [TestMethod]
  3250. public void Sftp_SftpFileStream_ReadAndWriteAsync()
  3251. {
  3252. TestReadAndWrite(
  3253. (s, buffer, offset, count) => s.ReadAsync(buffer, offset, count).GetAwaiter().GetResult(),
  3254. (s, buffer, offset, count) => s.WriteAsync(buffer, offset, count).GetAwaiter().GetResult());
  3255. }
  3256. [TestMethod]
  3257. public void Sftp_SftpFileStream_ReadAndWriteBeginEnd()
  3258. {
  3259. TestReadAndWrite(
  3260. (s, buffer, offset, count) => s.EndRead(s.BeginRead(buffer, offset, count, null, null)),
  3261. (s, buffer, offset, count) => s.EndWrite(s.BeginWrite(buffer, offset, count, null, null)));
  3262. }
  3263. #if NET
  3264. [TestMethod]
  3265. public void Sftp_SftpFileStream_ReadAndWriteSpan()
  3266. {
  3267. TestReadAndWrite(
  3268. (s, buffer, offset, count) => s.Read(buffer.AsSpan(offset, count)),
  3269. (s, buffer, offset, count) => s.Write(buffer.AsSpan(offset, count)));
  3270. }
  3271. [TestMethod]
  3272. public void Sftp_SftpFileStream_ReadAndWriteAsyncMemory()
  3273. {
  3274. TestReadAndWrite(
  3275. (s, buffer, offset, count) => s.ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(),
  3276. (s, buffer, offset, count) => s.WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult());
  3277. }
  3278. #endif
  3279. private void TestReadAndWrite(
  3280. Func<SftpFileStream, byte[], int, int, int> read,
  3281. Action<SftpFileStream, byte[], int, int> write)
  3282. {
  3283. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3284. {
  3285. client.Connect();
  3286. var remoteFile = GenerateUniqueRemoteFileName();
  3287. if (client.Exists(remoteFile))
  3288. {
  3289. client.DeleteFile(remoteFile);
  3290. }
  3291. try
  3292. {
  3293. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3294. {
  3295. Assert.IsFalse(s.CanRead);
  3296. Assert.IsTrue(s.CanWrite);
  3297. write(s, new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3298. }
  3299. // switch from read to write mode
  3300. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3301. {
  3302. Assert.IsTrue(s.CanRead);
  3303. Assert.IsTrue(s.CanWrite);
  3304. Assert.AreEqual(4, ReadByte(s));
  3305. Assert.AreEqual(3, ReadByte(s));
  3306. Assert.AreEqual(2, s.Position);
  3307. WriteByte(s, 7);
  3308. write(s, new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3309. Assert.AreEqual(6, s.Position);
  3310. }
  3311. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3312. {
  3313. Assert.IsTrue(s.CanRead);
  3314. Assert.IsFalse(s.CanWrite);
  3315. Assert.AreEqual(6, s.Length);
  3316. var buffer = new byte[s.Length];
  3317. Assert.AreEqual(6, read(s, buffer, 0, buffer.Length));
  3318. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3319. // Ensure we've reached end of the stream
  3320. Assert.AreEqual(-1, ReadByte(s));
  3321. }
  3322. // switch from read to write mode, and back to read mode and finally
  3323. // append a byte
  3324. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3325. {
  3326. Assert.AreEqual(4, ReadByte(s));
  3327. Assert.AreEqual(3, ReadByte(s));
  3328. Assert.AreEqual(7, ReadByte(s));
  3329. write(s, new byte[] { 0, 1, 6, 4 }, 1, 2);
  3330. Assert.AreEqual(11, ReadByte(s));
  3331. // Ensure we've reached end of the stream
  3332. Assert.AreEqual(-1, ReadByte(s));
  3333. WriteByte(s, 12);
  3334. }
  3335. // switch from write to read mode, and back to write mode
  3336. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3337. {
  3338. WriteByte(s, 5);
  3339. Assert.AreEqual(3, ReadByte(s));
  3340. WriteByte(s, 13);
  3341. Assert.AreEqual(3, s.Position);
  3342. }
  3343. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3344. {
  3345. Assert.AreEqual(7, s.Length);
  3346. var buffer = new byte[s.Length];
  3347. Assert.AreEqual(7, read(s, buffer, 0, buffer.Length));
  3348. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3349. // Ensure we've reached end of the stream
  3350. Assert.AreEqual(-1, ReadByte(s));
  3351. }
  3352. }
  3353. finally
  3354. {
  3355. if (client.Exists(remoteFile))
  3356. {
  3357. client.DeleteFile(remoteFile);
  3358. }
  3359. }
  3360. }
  3361. int ReadByte(SftpFileStream s)
  3362. {
  3363. var buffer = new byte[1];
  3364. var bytesRead = read(s, buffer, 0, 1);
  3365. return bytesRead == 0 ? -1 : buffer[0];
  3366. }
  3367. void WriteByte(SftpFileStream s, byte b)
  3368. {
  3369. write(s, [b], 0, 1);
  3370. }
  3371. }
  3372. [TestMethod]
  3373. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3374. {
  3375. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3376. {
  3377. client.Connect();
  3378. var remoteFile = GenerateUniqueRemoteFileName();
  3379. if (client.Exists(remoteFile))
  3380. {
  3381. client.DeleteFile(remoteFile);
  3382. }
  3383. try
  3384. {
  3385. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3386. {
  3387. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3388. }
  3389. // reduce length while in write mode, with data in write buffer, and before
  3390. // current position
  3391. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3392. {
  3393. s.Position = 3;
  3394. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3395. Assert.AreEqual(7, s.Position);
  3396. // verify buffer has not yet been flushed
  3397. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3398. {
  3399. Assert.AreEqual(4, fs.ReadByte());
  3400. Assert.AreEqual(3, fs.ReadByte());
  3401. Assert.AreEqual(2, fs.ReadByte());
  3402. // Ensure we've reached end of the stream
  3403. Assert.AreEqual(-1, fs.ReadByte());
  3404. }
  3405. s.SetLength(5);
  3406. Assert.AreEqual(5, s.Position);
  3407. // verify that buffer was flushed and size has been modified
  3408. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3409. {
  3410. Assert.AreEqual(4, fs.ReadByte());
  3411. Assert.AreEqual(3, fs.ReadByte());
  3412. Assert.AreEqual(2, fs.ReadByte());
  3413. Assert.AreEqual(6, fs.ReadByte());
  3414. Assert.AreEqual(7, fs.ReadByte());
  3415. // Ensure we've reached end of the stream
  3416. Assert.AreEqual(-1, fs.ReadByte());
  3417. }
  3418. s.WriteByte(1);
  3419. }
  3420. // verify that last byte was correctly written to the file
  3421. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3422. {
  3423. Assert.AreEqual(6, s.Length);
  3424. var buffer = new byte[s.Length + 2];
  3425. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3426. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3427. // Ensure we've reached end of the stream
  3428. Assert.AreEqual(-1, s.ReadByte());
  3429. }
  3430. // reduce length while in read mode, but beyond current position
  3431. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3432. {
  3433. var buffer = new byte[1];
  3434. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3435. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3436. s.SetLength(3);
  3437. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3438. {
  3439. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3440. }
  3441. // verify that position was not changed
  3442. Assert.AreEqual(1, s.Position);
  3443. // verify that read buffer was cleared
  3444. Assert.AreEqual(1, s.ReadByte());
  3445. Assert.AreEqual(6, s.ReadByte());
  3446. Assert.AreEqual(2, s.ReadByte());
  3447. // Ensure we've reached end of the stream
  3448. Assert.AreEqual(-1, s.ReadByte());
  3449. Assert.AreEqual(4, s.Length);
  3450. }
  3451. // reduce length while in read mode, but before current position
  3452. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3453. {
  3454. var buffer = new byte[4];
  3455. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3456. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3457. Assert.AreEqual(4, s.Position);
  3458. s.SetLength(3);
  3459. // verify that position was moved to last byte
  3460. Assert.AreEqual(3, s.Position);
  3461. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3462. {
  3463. Assert.AreEqual(3, w.Length);
  3464. Assert.AreEqual(8, w.ReadByte());
  3465. Assert.AreEqual(1, w.ReadByte());
  3466. Assert.AreEqual(6, w.ReadByte());
  3467. // Ensure we've reached end of the stream
  3468. Assert.AreEqual(-1, w.ReadByte());
  3469. }
  3470. // Ensure we've reached end of the stream
  3471. Assert.AreEqual(-1, s.ReadByte());
  3472. }
  3473. }
  3474. finally
  3475. {
  3476. if (client.Exists(remoteFile))
  3477. {
  3478. client.DeleteFile(remoteFile);
  3479. }
  3480. }
  3481. }
  3482. }
  3483. [TestMethod]
  3484. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3485. {
  3486. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3487. {
  3488. client.BufferSize = 500;
  3489. client.Connect();
  3490. var remoteFile = GenerateUniqueRemoteFileName();
  3491. if (client.Exists(remoteFile))
  3492. {
  3493. client.DeleteFile(remoteFile);
  3494. }
  3495. try
  3496. {
  3497. // create single-byte file
  3498. using (var fs = client.OpenWrite(remoteFile))
  3499. {
  3500. fs.WriteByte(0x04);
  3501. }
  3502. // seek beyond EOF but not beyond buffer size
  3503. // do not write anything
  3504. using (var fs = client.OpenWrite(remoteFile))
  3505. {
  3506. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3507. Assert.AreEqual(3, newPosition);
  3508. Assert.AreEqual(3, fs.Position);
  3509. Assert.AreEqual(1, fs.Length);
  3510. }
  3511. using (var fs = client.OpenRead(remoteFile))
  3512. {
  3513. Assert.AreEqual(1, fs.Length);
  3514. Assert.AreEqual(0x04, fs.ReadByte());
  3515. // Ensure we've reached end of the stream
  3516. Assert.AreEqual(-1, fs.ReadByte());
  3517. }
  3518. client.DeleteFile(remoteFile);
  3519. // create single-byte file
  3520. using (var fs = client.OpenWrite(remoteFile))
  3521. {
  3522. fs.WriteByte(0x04);
  3523. }
  3524. // seek beyond EOF and beyond buffer size
  3525. // do not write anything
  3526. using (var fs = client.OpenWrite(remoteFile))
  3527. {
  3528. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3529. Assert.AreEqual(700, newPosition);
  3530. Assert.AreEqual(700, fs.Position);
  3531. Assert.AreEqual(1, fs.Length);
  3532. }
  3533. using (var fs = client.OpenRead(remoteFile))
  3534. {
  3535. Assert.AreEqual(1, fs.Length);
  3536. Assert.AreEqual(0x04, fs.ReadByte());
  3537. // Ensure we've reached end of the stream
  3538. Assert.AreEqual(-1, fs.ReadByte());
  3539. }
  3540. client.DeleteFile(remoteFile);
  3541. // create single-byte file
  3542. using (var fs = client.OpenWrite(remoteFile))
  3543. {
  3544. fs.WriteByte(0x04);
  3545. }
  3546. // seek beyond EOF but not beyond buffer size
  3547. // write less bytes than buffer size
  3548. var seekOffset = 3L;
  3549. // buffer holding the data that we'll write to the file
  3550. var writeBuffer = GenerateRandom(size: 7);
  3551. using (var fs = client.OpenWrite(remoteFile))
  3552. {
  3553. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3554. Assert.AreEqual(seekOffset, newPosition);
  3555. Assert.AreEqual(seekOffset, fs.Position);
  3556. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3557. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3558. }
  3559. using (var fs = client.OpenRead(remoteFile))
  3560. {
  3561. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3562. Assert.AreEqual(0x04, fs.ReadByte());
  3563. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3564. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3565. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3566. var readBuffer = new byte[writeBuffer.Length];
  3567. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3568. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3569. // Ensure we've reached end of the stream
  3570. Assert.AreEqual(-1, fs.ReadByte());
  3571. }
  3572. client.DeleteFile(remoteFile);
  3573. // create single-byte file
  3574. using (var fs = client.OpenWrite(remoteFile))
  3575. {
  3576. fs.WriteByte(0x04);
  3577. }
  3578. // seek beyond EOF and beyond buffer size
  3579. // write less bytes than buffer size
  3580. seekOffset = 700L;
  3581. // buffer holding the data that we'll write to the file
  3582. writeBuffer = GenerateRandom(size: 4);
  3583. using (var fs = client.OpenWrite(remoteFile))
  3584. {
  3585. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3586. Assert.AreEqual(seekOffset, newPosition);
  3587. Assert.AreEqual(seekOffset, fs.Position);
  3588. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3589. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3590. }
  3591. using (var fs = client.OpenRead(remoteFile))
  3592. {
  3593. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3594. Assert.AreEqual(0x04, fs.ReadByte());
  3595. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3596. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3597. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3598. var readBuffer = new byte[writeBuffer.Length];
  3599. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3600. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3601. // Ensure we've reached end of the stream
  3602. Assert.AreEqual(-1, fs.ReadByte());
  3603. }
  3604. client.DeleteFile(remoteFile);
  3605. // create single-byte file
  3606. using (var fs = client.OpenWrite(remoteFile))
  3607. {
  3608. fs.WriteByte(0x04);
  3609. }
  3610. // seek beyond EOF but not beyond buffer size
  3611. // write more bytes than buffer size
  3612. writeBuffer = GenerateRandom(size: 600);
  3613. using (var fs = client.OpenWrite(remoteFile))
  3614. {
  3615. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3616. Assert.AreEqual(3, newPosition);
  3617. Assert.AreEqual(3, fs.Position);
  3618. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3619. }
  3620. using (var fs = client.OpenRead(remoteFile))
  3621. {
  3622. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3623. Assert.AreEqual(0x04, fs.ReadByte());
  3624. Assert.AreEqual(0x00, fs.ReadByte());
  3625. Assert.AreEqual(0x00, fs.ReadByte());
  3626. var readBuffer = new byte[writeBuffer.Length];
  3627. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3628. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3629. // Ensure we've reached end of the stream
  3630. Assert.AreEqual(-1, fs.ReadByte());
  3631. }
  3632. client.DeleteFile(remoteFile);
  3633. // create single-byte file
  3634. using (var fs = client.OpenWrite(remoteFile))
  3635. {
  3636. fs.WriteByte(0x04);
  3637. }
  3638. // seek beyond EOF and beyond buffer size
  3639. // write more bytes than buffer size
  3640. writeBuffer = GenerateRandom(size: 600);
  3641. using (var fs = client.OpenWrite(remoteFile))
  3642. {
  3643. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3644. Assert.AreEqual(550, newPosition);
  3645. Assert.AreEqual(550, fs.Position);
  3646. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3647. }
  3648. using (var fs = client.OpenRead(remoteFile))
  3649. {
  3650. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3651. Assert.AreEqual(0x04, fs.ReadByte());
  3652. var soughtOverReadBuffer = new byte[550 - 1];
  3653. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3654. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3655. var readBuffer = new byte[writeBuffer.Length];
  3656. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3657. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3658. // Ensure we've reached end of the stream
  3659. Assert.AreEqual(-1, fs.ReadByte());
  3660. }
  3661. }
  3662. finally
  3663. {
  3664. if (client.Exists(remoteFile))
  3665. {
  3666. client.DeleteFile(remoteFile);
  3667. }
  3668. }
  3669. }
  3670. }
  3671. [TestMethod]
  3672. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3673. {
  3674. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3675. {
  3676. client.BufferSize = 500;
  3677. client.Connect();
  3678. var remoteFile = GenerateUniqueRemoteFileName();
  3679. if (client.Exists(remoteFile))
  3680. {
  3681. client.DeleteFile(remoteFile);
  3682. }
  3683. try
  3684. {
  3685. // create single-byte file
  3686. using (var fs = client.OpenWrite(remoteFile))
  3687. {
  3688. fs.WriteByte(0x04);
  3689. }
  3690. // seek beyond EOF but not beyond buffer size
  3691. // do not write anything
  3692. using (var fs = client.OpenWrite(remoteFile))
  3693. {
  3694. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3695. Assert.AreEqual(4, newPosition);
  3696. Assert.AreEqual(4, fs.Position);
  3697. Assert.AreEqual(1, fs.Length);
  3698. }
  3699. using (var fs = client.OpenRead(remoteFile))
  3700. {
  3701. Assert.AreEqual(1, fs.Length);
  3702. Assert.AreEqual(0x04, fs.ReadByte());
  3703. // Ensure we've reached end of the stream
  3704. Assert.AreEqual(-1, fs.ReadByte());
  3705. }
  3706. client.DeleteFile(remoteFile);
  3707. // create single-byte file
  3708. using (var fs = client.OpenWrite(remoteFile))
  3709. {
  3710. fs.WriteByte(0x04);
  3711. }
  3712. // seek beyond EOF and beyond buffer size
  3713. // do not write anything
  3714. using (var fs = client.OpenWrite(remoteFile))
  3715. {
  3716. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3717. Assert.AreEqual(701, newPosition);
  3718. Assert.AreEqual(701, fs.Position);
  3719. Assert.AreEqual(1, fs.Length);
  3720. }
  3721. using (var fs = client.OpenRead(remoteFile))
  3722. {
  3723. Assert.AreEqual(1, fs.Length);
  3724. Assert.AreEqual(0x04, fs.ReadByte());
  3725. // Ensure we've reached end of the stream
  3726. Assert.AreEqual(-1, fs.ReadByte());
  3727. }
  3728. client.DeleteFile(remoteFile);
  3729. // create single-byte file
  3730. using (var fs = client.OpenWrite(remoteFile))
  3731. {
  3732. fs.WriteByte(0x04);
  3733. }
  3734. // seek beyond EOF but not beyond buffer size
  3735. // write less bytes than buffer size
  3736. var seekOffset = 3L;
  3737. // buffer holding the data that we'll write to the file
  3738. var writeBuffer = GenerateRandom(size: 7);
  3739. using (var fs = client.OpenWrite(remoteFile))
  3740. {
  3741. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3742. Assert.AreEqual(4, newPosition);
  3743. Assert.AreEqual(4, fs.Position);
  3744. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3745. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3746. }
  3747. using (var fs = client.OpenRead(remoteFile))
  3748. {
  3749. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3750. Assert.AreEqual(0x04, fs.ReadByte());
  3751. var soughtOverReadBuffer = new byte[seekOffset];
  3752. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3753. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3754. var readBuffer = new byte[writeBuffer.Length];
  3755. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3756. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3757. // Ensure we've reached end of the stream
  3758. Assert.AreEqual(-1, fs.ReadByte());
  3759. }
  3760. client.DeleteFile(remoteFile);
  3761. // create single-byte file
  3762. using (var fs = client.OpenWrite(remoteFile))
  3763. {
  3764. fs.WriteByte(0x04);
  3765. }
  3766. // seek beyond EOF and beyond buffer size
  3767. // write less bytes than buffer size
  3768. seekOffset = 700L;
  3769. // buffer holding the data that we'll write to the file
  3770. writeBuffer = GenerateRandom(size: 4);
  3771. using (var fs = client.OpenWrite(remoteFile))
  3772. {
  3773. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3774. Assert.AreEqual(1 + seekOffset, newPosition);
  3775. Assert.AreEqual(1 + seekOffset, fs.Position);
  3776. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3777. }
  3778. using (var fs = client.OpenRead(remoteFile))
  3779. {
  3780. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3781. Assert.AreEqual(0x04, fs.ReadByte());
  3782. var soughtOverReadBuffer = new byte[seekOffset];
  3783. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3784. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3785. var readBuffer = new byte[writeBuffer.Length];
  3786. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3787. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3788. // Ensure we've reached end of the stream
  3789. Assert.AreEqual(-1, fs.ReadByte());
  3790. }
  3791. client.DeleteFile(remoteFile);
  3792. // create single-byte file
  3793. using (var fs = client.OpenWrite(remoteFile))
  3794. {
  3795. fs.WriteByte(0x04);
  3796. }
  3797. // seek beyond EOF but not beyond buffer size
  3798. // write more bytes than buffer size
  3799. seekOffset = 3L;
  3800. writeBuffer = GenerateRandom(size: 600);
  3801. using (var fs = client.OpenWrite(remoteFile))
  3802. {
  3803. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3804. Assert.AreEqual(1 + seekOffset, newPosition);
  3805. Assert.AreEqual(1 + seekOffset, fs.Position);
  3806. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3807. }
  3808. using (var fs = client.OpenRead(remoteFile))
  3809. {
  3810. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3811. Assert.AreEqual(0x04, fs.ReadByte());
  3812. var soughtOverReadBuffer = new byte[seekOffset];
  3813. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3814. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3815. var readBuffer = new byte[writeBuffer.Length];
  3816. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3817. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3818. // Ensure we've reached end of the stream
  3819. Assert.AreEqual(-1, fs.ReadByte());
  3820. }
  3821. client.DeleteFile(remoteFile);
  3822. // create single-byte file
  3823. using (var fs = client.OpenWrite(remoteFile))
  3824. {
  3825. fs.WriteByte(0x04);
  3826. }
  3827. // seek beyond EOF and beyond buffer size
  3828. // write more bytes than buffer size
  3829. seekOffset = 550L;
  3830. writeBuffer = GenerateRandom(size: 600);
  3831. using (var fs = client.OpenWrite(remoteFile))
  3832. {
  3833. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3834. Assert.AreEqual(1 + seekOffset, newPosition);
  3835. Assert.AreEqual(1 + seekOffset, fs.Position);
  3836. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3837. }
  3838. using (var fs = client.OpenRead(remoteFile))
  3839. {
  3840. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3841. Assert.AreEqual(0x04, fs.ReadByte());
  3842. var soughtOverReadBuffer = new byte[seekOffset];
  3843. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3844. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3845. var readBuffer = new byte[writeBuffer.Length];
  3846. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3847. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3848. // Ensure we've reached end of the stream
  3849. Assert.AreEqual(-1, fs.ReadByte());
  3850. }
  3851. }
  3852. finally
  3853. {
  3854. if (client.Exists(remoteFile))
  3855. {
  3856. client.DeleteFile(remoteFile);
  3857. }
  3858. }
  3859. }
  3860. }
  3861. [TestMethod]
  3862. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3863. {
  3864. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3865. {
  3866. client.BufferSize = 500;
  3867. client.Connect();
  3868. var remoteFile = GenerateUniqueRemoteFileName();
  3869. if (client.Exists(remoteFile))
  3870. {
  3871. client.DeleteFile(remoteFile);
  3872. }
  3873. try
  3874. {
  3875. using (var fs = client.OpenWrite(remoteFile))
  3876. {
  3877. fs.WriteByte(0x04);
  3878. fs.WriteByte(0x07);
  3879. fs.WriteByte(0x05);
  3880. }
  3881. // seek within file and not beyond buffer size
  3882. // do not write anything
  3883. using (var fs = client.OpenWrite(remoteFile))
  3884. {
  3885. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3886. Assert.AreEqual(1, newPosition);
  3887. Assert.AreEqual(1, fs.Position);
  3888. }
  3889. using (var fs = client.OpenRead(remoteFile))
  3890. {
  3891. Assert.AreEqual(3, fs.Length);
  3892. Assert.AreEqual(0x04, fs.ReadByte());
  3893. Assert.AreEqual(0x07, fs.ReadByte());
  3894. Assert.AreEqual(0x05, fs.ReadByte());
  3895. // Ensure we've reached end of the stream
  3896. Assert.AreEqual(-1, fs.ReadByte());
  3897. }
  3898. client.DeleteFile(remoteFile);
  3899. // buffer holding the data that we'll write to the file
  3900. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  3901. using (var fs = client.OpenWrite(remoteFile))
  3902. {
  3903. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3904. }
  3905. // seek within EOF and beyond buffer size
  3906. // do not write anything
  3907. using (var fs = client.OpenWrite(remoteFile))
  3908. {
  3909. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3910. Assert.AreEqual(600, newPosition);
  3911. Assert.AreEqual(600, fs.Position);
  3912. }
  3913. using (var fs = client.OpenRead(remoteFile))
  3914. {
  3915. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3916. var readBuffer = new byte[writeBuffer.Length];
  3917. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3918. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3919. // Ensure we've reached end of the stream
  3920. Assert.AreEqual(-1, fs.ReadByte());
  3921. }
  3922. client.DeleteFile(remoteFile);
  3923. // seek within EOF and within buffer size
  3924. // write less bytes than buffer size
  3925. using (var fs = client.OpenWrite(remoteFile))
  3926. {
  3927. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3928. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3929. Assert.AreEqual(697, newPosition);
  3930. Assert.AreEqual(697, fs.Position);
  3931. fs.WriteByte(0x01);
  3932. fs.WriteByte(0x05);
  3933. fs.WriteByte(0x04);
  3934. fs.WriteByte(0x07);
  3935. }
  3936. using (var fs = client.OpenRead(remoteFile))
  3937. {
  3938. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3939. var readBuffer = new byte[writeBuffer.Length - 3];
  3940. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3941. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3942. Assert.AreEqual(0x01, fs.ReadByte());
  3943. Assert.AreEqual(0x05, fs.ReadByte());
  3944. Assert.AreEqual(0x04, fs.ReadByte());
  3945. Assert.AreEqual(0x07, fs.ReadByte());
  3946. // Ensure we've reached end of the stream
  3947. Assert.AreEqual(-1, fs.ReadByte());
  3948. }
  3949. client.DeleteFile(remoteFile);
  3950. // buffer holding the data that we'll write to the file
  3951. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  3952. // seek within EOF and beyond buffer size
  3953. // write less bytes than buffer size
  3954. using (var fs = client.OpenWrite(remoteFile))
  3955. {
  3956. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3957. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3958. Assert.AreEqual(1000, newPosition);
  3959. Assert.AreEqual(1000, fs.Position);
  3960. fs.WriteByte(0x01);
  3961. fs.WriteByte(0x05);
  3962. fs.WriteByte(0x04);
  3963. fs.WriteByte(0x07);
  3964. }
  3965. using (var fs = client.OpenRead(remoteFile))
  3966. {
  3967. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3968. // First part of file should not have been touched
  3969. var readBuffer = new byte[(int)client.BufferSize * 2];
  3970. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3971. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3972. // Check part that should have been updated
  3973. Assert.AreEqual(0x01, fs.ReadByte());
  3974. Assert.AreEqual(0x05, fs.ReadByte());
  3975. Assert.AreEqual(0x04, fs.ReadByte());
  3976. Assert.AreEqual(0x07, fs.ReadByte());
  3977. // Remaining bytes should not have been touched
  3978. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  3979. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3980. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  3981. // Ensure we've reached end of the stream
  3982. Assert.AreEqual(-1, fs.ReadByte());
  3983. }
  3984. }
  3985. finally
  3986. {
  3987. if (client.Exists(remoteFile))
  3988. {
  3989. client.DeleteFile(remoteFile);
  3990. }
  3991. }
  3992. }
  3993. }
  3994. /// https://github.com/sshnet/SSH.NET/issues/253
  3995. [TestMethod]
  3996. public void Sftp_SftpFileStream_Seek_Issue253()
  3997. {
  3998. var buf = Encoding.UTF8.GetBytes("123456");
  3999. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4000. {
  4001. client.Connect();
  4002. var remoteFile = GenerateUniqueRemoteFileName();
  4003. if (client.Exists(remoteFile))
  4004. {
  4005. client.DeleteFile(remoteFile);
  4006. }
  4007. try
  4008. {
  4009. using (var ws = client.OpenWrite(remoteFile))
  4010. {
  4011. ws.Write(buf, offset: 0, count: 3);
  4012. }
  4013. using (var ws = client.OpenWrite(remoteFile))
  4014. {
  4015. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4016. Assert.AreEqual(3, newPosition);
  4017. Assert.AreEqual(3, ws.Position);
  4018. ws.Write(buf, 3, 3);
  4019. }
  4020. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4021. Assert.AreEqual("123456", actual);
  4022. }
  4023. finally
  4024. {
  4025. if (client.Exists(remoteFile))
  4026. {
  4027. client.DeleteFile(remoteFile);
  4028. }
  4029. }
  4030. }
  4031. }
  4032. [TestMethod]
  4033. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4034. {
  4035. var originalContent = GenerateRandom(size: 800);
  4036. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4037. {
  4038. client.BufferSize = 500;
  4039. client.Connect();
  4040. var remoteFile = GenerateUniqueRemoteFileName();
  4041. if (client.Exists(remoteFile))
  4042. {
  4043. client.DeleteFile(remoteFile);
  4044. }
  4045. try
  4046. {
  4047. using (var fs = client.OpenWrite(remoteFile))
  4048. {
  4049. fs.Write(originalContent, offset: 0, originalContent.Length);
  4050. }
  4051. using (var fs = client.OpenRead(remoteFile))
  4052. {
  4053. var readBuffer = new byte[200];
  4054. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4055. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4056. Assert.AreEqual(3L, newPosition);
  4057. Assert.AreEqual(3L, fs.Position);
  4058. }
  4059. client.DeleteFile(remoteFile);
  4060. #region Seek beyond EOF and beyond buffer size do not write anything
  4061. // create single-byte file
  4062. using (var fs = client.OpenWrite(remoteFile))
  4063. {
  4064. fs.WriteByte(0x04);
  4065. }
  4066. using (var fs = client.OpenRead(remoteFile))
  4067. {
  4068. Assert.AreEqual(1, fs.Length);
  4069. Assert.AreEqual(0x04, fs.ReadByte());
  4070. // Ensure we've reached end of the stream
  4071. Assert.AreEqual(-1, fs.ReadByte());
  4072. }
  4073. using (var fs = client.OpenWrite(remoteFile))
  4074. {
  4075. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4076. Assert.AreEqual(700L, newPosition);
  4077. Assert.AreEqual(700L, fs.Position);
  4078. }
  4079. using (var fs = client.OpenRead(remoteFile))
  4080. {
  4081. Assert.AreEqual(1, fs.Length);
  4082. Assert.AreEqual(0x04, fs.ReadByte());
  4083. // Ensure we've reached end of the stream
  4084. Assert.AreEqual(-1, fs.ReadByte());
  4085. }
  4086. client.DeleteFile(remoteFile);
  4087. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4088. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4089. // create single-byte file
  4090. using (var fs = client.OpenWrite(remoteFile))
  4091. {
  4092. fs.WriteByte(0x04);
  4093. }
  4094. var seekOffset = 3L;
  4095. var writeBuffer = GenerateRandom(size: 7);
  4096. using (var fs = client.OpenWrite(remoteFile))
  4097. {
  4098. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4099. Assert.AreEqual(seekOffset, newPosition);
  4100. Assert.AreEqual(seekOffset, fs.Position);
  4101. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4102. }
  4103. using (var fs = client.OpenRead(remoteFile))
  4104. {
  4105. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4106. Assert.AreEqual(0x04, fs.ReadByte());
  4107. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4108. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4109. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4110. var readBuffer = new byte[writeBuffer.Length];
  4111. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4112. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4113. // Ensure we've reached end of the stream
  4114. Assert.AreEqual(-1, fs.ReadByte());
  4115. }
  4116. client.DeleteFile(remoteFile);
  4117. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4118. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4119. // create single-byte file
  4120. using (var fs = client.OpenWrite(remoteFile))
  4121. {
  4122. fs.WriteByte(0x04);
  4123. }
  4124. seekOffset = 700L;
  4125. writeBuffer = GenerateRandom(size: 4);
  4126. using (var fs = client.OpenWrite(remoteFile))
  4127. {
  4128. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4129. Assert.AreEqual(seekOffset, newPosition);
  4130. Assert.AreEqual(seekOffset, fs.Position);
  4131. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4132. }
  4133. using (var fs = client.OpenRead(remoteFile))
  4134. {
  4135. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4136. Assert.AreEqual(0x04, fs.ReadByte());
  4137. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4138. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4139. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4140. var readBuffer = new byte[writeBuffer.Length];
  4141. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4142. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4143. // Ensure we've reached end of the stream
  4144. Assert.AreEqual(-1, fs.ReadByte());
  4145. }
  4146. client.DeleteFile(remoteFile);
  4147. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4148. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4149. // create single-byte file
  4150. using (var fs = client.OpenWrite(remoteFile))
  4151. {
  4152. fs.WriteByte(0x04);
  4153. }
  4154. seekOffset = 3L;
  4155. writeBuffer = GenerateRandom(size: 600);
  4156. using (var fs = client.OpenWrite(remoteFile))
  4157. {
  4158. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4159. Assert.AreEqual(seekOffset, newPosition);
  4160. Assert.AreEqual(seekOffset, fs.Position);
  4161. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4162. }
  4163. using (var fs = client.OpenRead(remoteFile))
  4164. {
  4165. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4166. Assert.AreEqual(0x04, fs.ReadByte());
  4167. Assert.AreEqual(0x00, fs.ReadByte());
  4168. Assert.AreEqual(0x00, fs.ReadByte());
  4169. var readBuffer = new byte[writeBuffer.Length];
  4170. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4171. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4172. // Ensure we've reached end of the stream
  4173. Assert.AreEqual(-1, fs.ReadByte());
  4174. }
  4175. client.DeleteFile(remoteFile);
  4176. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4177. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4178. // create single-byte file
  4179. using (var fs = client.OpenWrite(remoteFile))
  4180. {
  4181. fs.WriteByte(0x04);
  4182. }
  4183. seekOffset = 550L;
  4184. writeBuffer = GenerateRandom(size: 600);
  4185. using (var fs = client.OpenWrite(remoteFile))
  4186. {
  4187. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4188. Assert.AreEqual(seekOffset, newPosition);
  4189. Assert.AreEqual(seekOffset, fs.Position);
  4190. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4191. }
  4192. using (var fs = client.OpenRead(remoteFile))
  4193. {
  4194. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4195. Assert.AreEqual(0x04, fs.ReadByte());
  4196. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4197. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4198. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBuffer));
  4199. var readBuffer = new byte[writeBuffer.Length];
  4200. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4201. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4202. // Ensure we've reached end of the stream
  4203. Assert.AreEqual(-1, fs.ReadByte());
  4204. }
  4205. client.DeleteFile(remoteFile);
  4206. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4207. }
  4208. finally
  4209. {
  4210. if (client.Exists(remoteFile))
  4211. {
  4212. client.DeleteFile(remoteFile);
  4213. }
  4214. }
  4215. }
  4216. }
  4217. [TestMethod]
  4218. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4219. {
  4220. var size = new Random().Next(500, 5000);
  4221. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4222. {
  4223. client.Connect();
  4224. var remoteFile = GenerateUniqueRemoteFileName();
  4225. if (client.Exists(remoteFile))
  4226. {
  4227. client.DeleteFile(remoteFile);
  4228. }
  4229. try
  4230. {
  4231. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4232. {
  4233. s.SetLength(size);
  4234. }
  4235. Assert.IsTrue(client.Exists(remoteFile));
  4236. var attributes = client.GetAttributes(remoteFile);
  4237. Assert.IsTrue(attributes.IsRegularFile);
  4238. Assert.AreEqual(size, attributes.Size);
  4239. using (var downloaded = new MemoryStream())
  4240. {
  4241. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4242. downloaded.Position = 0;
  4243. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4244. }
  4245. }
  4246. finally
  4247. {
  4248. if (client.Exists(remoteFile))
  4249. {
  4250. client.DeleteFile(remoteFile);
  4251. }
  4252. }
  4253. }
  4254. }
  4255. [TestMethod]
  4256. public void Sftp_Open_Append_Write_ExistingFile()
  4257. {
  4258. const int fileSize = 5 * 1024;
  4259. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4260. using (var input = CreateMemoryStream(fileSize))
  4261. {
  4262. input.Position = 0;
  4263. client.Connect();
  4264. var remoteFile = GenerateUniqueRemoteFileName();
  4265. if (client.Exists(remoteFile))
  4266. {
  4267. client.DeleteFile(remoteFile);
  4268. }
  4269. try
  4270. {
  4271. client.UploadFile(input, remoteFile);
  4272. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4273. {
  4274. Assert.IsFalse(s.CanRead);
  4275. Assert.IsTrue(s.CanWrite);
  4276. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4277. s.Write(buffer, offset: 0, buffer.Length);
  4278. input.Write(buffer, offset: 0, buffer.Length);
  4279. }
  4280. using (var downloaded = new MemoryStream())
  4281. {
  4282. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4283. input.Position = 0;
  4284. downloaded.Position = 0;
  4285. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4286. }
  4287. }
  4288. finally
  4289. {
  4290. if (client.Exists(remoteFile))
  4291. {
  4292. client.DeleteFile(remoteFile);
  4293. }
  4294. }
  4295. }
  4296. }
  4297. [TestMethod]
  4298. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4299. {
  4300. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4301. {
  4302. client.Connect();
  4303. var remoteFile = GenerateUniqueRemoteFileName();
  4304. if (client.Exists(remoteFile))
  4305. {
  4306. client.DeleteFile(remoteFile);
  4307. }
  4308. try
  4309. {
  4310. #region Verify if merely opening the file for append creates a zero-byte file
  4311. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4312. {
  4313. }
  4314. Assert.IsTrue(client.Exists(remoteFile));
  4315. var attributes = client.GetAttributes(remoteFile);
  4316. Assert.IsTrue(attributes.IsRegularFile);
  4317. Assert.AreEqual(0L, attributes.Size);
  4318. #endregion Verify if merely opening the file for append creates it
  4319. client.DeleteFile(remoteFile);
  4320. #region Verify if content is actually written to the file
  4321. var content = GenerateRandom(size: 100);
  4322. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4323. {
  4324. s.Write(content, offset: 0, content.Length);
  4325. }
  4326. using (var downloaded = new MemoryStream())
  4327. {
  4328. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4329. downloaded.Position = 0;
  4330. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4331. }
  4332. #endregion Verify if content is actually written to the file
  4333. }
  4334. finally
  4335. {
  4336. if (client.Exists(remoteFile))
  4337. {
  4338. client.DeleteFile(remoteFile);
  4339. }
  4340. }
  4341. }
  4342. }
  4343. [TestMethod]
  4344. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4345. {
  4346. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4347. {
  4348. client.Connect();
  4349. var remoteFile = GenerateUniqueRemoteFileName();
  4350. if (client.Exists(remoteFile))
  4351. {
  4352. client.DeleteFile(remoteFile);
  4353. }
  4354. try
  4355. {
  4356. #region Verify if merely opening the file for create creates a zero-byte file
  4357. using (client.Open(remoteFile, FileMode.Create))
  4358. {
  4359. }
  4360. Assert.IsTrue(client.Exists(remoteFile));
  4361. var attributes = client.GetAttributes(remoteFile);
  4362. Assert.IsTrue(attributes.IsRegularFile);
  4363. Assert.AreEqual(0L, attributes.Size);
  4364. #endregion Verify if merely opening the file for create creates a zero-byte file
  4365. client.DeleteFile(remoteFile);
  4366. #region Verify if content is actually written to the file
  4367. var content = GenerateRandom(size: 100);
  4368. using (var s = client.Open(remoteFile, FileMode.Create))
  4369. {
  4370. Assert.IsTrue(s.CanRead);
  4371. Assert.IsTrue(s.CanWrite);
  4372. s.Write(content, offset: 0, content.Length);
  4373. }
  4374. using (var downloaded = new MemoryStream())
  4375. {
  4376. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4377. downloaded.Position = 0;
  4378. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4379. }
  4380. #endregion Verify if content is actually written to the file
  4381. }
  4382. finally
  4383. {
  4384. if (client.Exists(remoteFile))
  4385. {
  4386. client.DeleteFile(remoteFile);
  4387. }
  4388. }
  4389. }
  4390. }
  4391. [TestMethod]
  4392. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4393. {
  4394. const int fileSize = 5 * 1024;
  4395. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4396. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4397. using (var input = CreateMemoryStream(fileSize))
  4398. {
  4399. client.Connect();
  4400. var remoteFile = GenerateUniqueRemoteFileName();
  4401. if (client.Exists(remoteFile))
  4402. {
  4403. client.DeleteFile(remoteFile);
  4404. }
  4405. try
  4406. {
  4407. input.Position = 0;
  4408. client.UploadFile(input, remoteFile);
  4409. using (var stream = client.Open(remoteFile, FileMode.Create))
  4410. {
  4411. // Verify if merely opening the file for create overwrites the file
  4412. var attributes = client.GetAttributes(remoteFile);
  4413. Assert.IsTrue(attributes.IsRegularFile);
  4414. Assert.AreEqual(0L, attributes.Size);
  4415. stream.Write(newContent, offset: 0, newContent.Length);
  4416. stream.Position = 0;
  4417. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4418. }
  4419. }
  4420. finally
  4421. {
  4422. if (client.Exists(remoteFile))
  4423. {
  4424. client.DeleteFile(remoteFile);
  4425. }
  4426. }
  4427. }
  4428. }
  4429. [TestMethod]
  4430. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4431. {
  4432. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4433. {
  4434. client.Connect();
  4435. var remoteFile = GenerateUniqueRemoteFileName();
  4436. if (client.Exists(remoteFile))
  4437. {
  4438. client.DeleteFile(remoteFile);
  4439. }
  4440. try
  4441. {
  4442. #region Verify if merely opening the file for create creates a zero-byte file
  4443. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4444. {
  4445. }
  4446. Assert.IsTrue(client.Exists(remoteFile));
  4447. var attributes = client.GetAttributes(remoteFile);
  4448. Assert.IsTrue(attributes.IsRegularFile);
  4449. Assert.AreEqual(0L, attributes.Size);
  4450. #endregion Verify if merely opening the file for create creates a zero-byte file
  4451. client.DeleteFile(remoteFile);
  4452. #region Verify if content is actually written to the file
  4453. var content = GenerateRandom(size: 100);
  4454. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4455. {
  4456. s.Write(content, offset: 0, content.Length);
  4457. }
  4458. using (var downloaded = new MemoryStream())
  4459. {
  4460. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4461. downloaded.Position = 0;
  4462. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4463. }
  4464. #endregion Verify if content is actually written to the file
  4465. }
  4466. finally
  4467. {
  4468. if (client.Exists(remoteFile))
  4469. {
  4470. client.DeleteFile(remoteFile);
  4471. }
  4472. }
  4473. }
  4474. }
  4475. [TestMethod]
  4476. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4477. {
  4478. const int fileSize = 5 * 1024;
  4479. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4480. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4481. using (var input = CreateMemoryStream(fileSize))
  4482. {
  4483. client.Connect();
  4484. var remoteFile = GenerateUniqueRemoteFileName();
  4485. if (client.Exists(remoteFile))
  4486. {
  4487. client.DeleteFile(remoteFile);
  4488. }
  4489. try
  4490. {
  4491. input.Position = 0;
  4492. client.UploadFile(input, remoteFile);
  4493. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4494. {
  4495. // Verify if merely opening the file for create overwrites the file
  4496. var attributes = client.GetAttributes(remoteFile);
  4497. Assert.IsTrue(attributes.IsRegularFile);
  4498. Assert.AreEqual(0L, attributes.Size);
  4499. stream.Write(newContent, offset: 0, newContent.Length);
  4500. stream.Position = 0;
  4501. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4502. }
  4503. }
  4504. finally
  4505. {
  4506. if (client.Exists(remoteFile))
  4507. {
  4508. client.DeleteFile(remoteFile);
  4509. }
  4510. }
  4511. }
  4512. }
  4513. [TestMethod]
  4514. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4515. {
  4516. // use new content that contains less bytes than original content to
  4517. // verify whether file is first truncated
  4518. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4519. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4520. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4521. {
  4522. client.Connect();
  4523. var remoteFile = GenerateUniqueRemoteFileName();
  4524. if (client.Exists(remoteFile))
  4525. {
  4526. client.DeleteFile(remoteFile);
  4527. }
  4528. try
  4529. {
  4530. client.WriteAllBytes(remoteFile, originalContent);
  4531. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4532. {
  4533. s.Write(newContent, offset: 0, newContent.Length);
  4534. }
  4535. using (var downloaded = new MemoryStream())
  4536. {
  4537. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4538. downloaded.Position = 0;
  4539. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4540. }
  4541. }
  4542. finally
  4543. {
  4544. if (client.Exists(remoteFile))
  4545. {
  4546. client.DeleteFile(remoteFile);
  4547. }
  4548. }
  4549. }
  4550. }
  4551. [TestMethod]
  4552. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4553. {
  4554. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4555. {
  4556. client.Connect();
  4557. var remoteFile = GenerateUniqueRemoteFileName();
  4558. if (client.Exists(remoteFile))
  4559. {
  4560. client.DeleteFile(remoteFile);
  4561. }
  4562. try
  4563. {
  4564. #region Verify if merely opening the file for create creates a zero-byte file
  4565. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4566. {
  4567. }
  4568. Assert.IsTrue(client.Exists(remoteFile));
  4569. var attributes = client.GetAttributes(remoteFile);
  4570. Assert.IsTrue(attributes.IsRegularFile);
  4571. Assert.AreEqual(0L, attributes.Size);
  4572. #endregion Verify if merely opening the file for create creates a zero-byte file
  4573. client.DeleteFile(remoteFile);
  4574. #region Verify if content is actually written to the file
  4575. var content = GenerateRandom(size: 100);
  4576. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4577. {
  4578. s.Write(content, offset: 0, content.Length);
  4579. }
  4580. using (var downloaded = new MemoryStream())
  4581. {
  4582. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4583. downloaded.Position = 0;
  4584. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4585. }
  4586. #endregion Verify if content is actually written to the file
  4587. }
  4588. finally
  4589. {
  4590. if (client.Exists(remoteFile))
  4591. {
  4592. client.DeleteFile(remoteFile);
  4593. }
  4594. }
  4595. }
  4596. }
  4597. [TestMethod]
  4598. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4599. {
  4600. const int fileSize = 5 * 1024;
  4601. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4602. using (var input = CreateMemoryStream(fileSize))
  4603. {
  4604. client.Connect();
  4605. var remoteFile = GenerateUniqueRemoteFileName();
  4606. if (client.Exists(remoteFile))
  4607. {
  4608. client.DeleteFile(remoteFile);
  4609. }
  4610. input.Position = 0;
  4611. try
  4612. {
  4613. client.UploadFile(input, remoteFile);
  4614. Stream stream = null;
  4615. try
  4616. {
  4617. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4618. Assert.Fail();
  4619. }
  4620. catch (SshException)
  4621. {
  4622. }
  4623. finally
  4624. {
  4625. stream?.Dispose();
  4626. }
  4627. // Verify that the file was not modified
  4628. using (var downloaded = new MemoryStream())
  4629. {
  4630. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4631. input.Position = 0;
  4632. downloaded.Position = 0;
  4633. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4634. }
  4635. }
  4636. finally
  4637. {
  4638. if (client.Exists(remoteFile))
  4639. {
  4640. client.DeleteFile(remoteFile);
  4641. }
  4642. }
  4643. }
  4644. }
  4645. [TestMethod]
  4646. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4647. {
  4648. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4649. {
  4650. client.Connect();
  4651. var remoteFile = GenerateUniqueRemoteFileName();
  4652. if (client.Exists(remoteFile))
  4653. {
  4654. client.DeleteFile(remoteFile);
  4655. }
  4656. try
  4657. {
  4658. #region Verify if merely opening the file creates a zero-byte file
  4659. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4660. {
  4661. }
  4662. Assert.IsTrue(client.Exists(remoteFile));
  4663. var attributes = client.GetAttributes(remoteFile);
  4664. Assert.IsTrue(attributes.IsRegularFile);
  4665. Assert.AreEqual(0L, attributes.Size);
  4666. #endregion Verify if merely opening the file creates it
  4667. client.DeleteFile(remoteFile);
  4668. #region Verify if content is actually written to the file
  4669. var content = GenerateRandom(size: 100);
  4670. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4671. {
  4672. s.Write(content, offset: 0, content.Length);
  4673. }
  4674. using (var downloaded = new MemoryStream())
  4675. {
  4676. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4677. downloaded.Position = 0;
  4678. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4679. }
  4680. #endregion Verify if content is actually written to the file
  4681. }
  4682. finally
  4683. {
  4684. if (client.Exists(remoteFile))
  4685. {
  4686. client.DeleteFile(remoteFile);
  4687. }
  4688. }
  4689. }
  4690. }
  4691. [TestMethod]
  4692. public void Sftp_Open_Open_Write_ExistingFile()
  4693. {
  4694. // use new content that contains less bytes than original content to
  4695. // verify whether file is first truncated
  4696. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4697. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4698. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4699. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4700. {
  4701. client.Connect();
  4702. var remoteFile = GenerateUniqueRemoteFileName();
  4703. if (client.Exists(remoteFile))
  4704. {
  4705. client.DeleteFile(remoteFile);
  4706. }
  4707. try
  4708. {
  4709. client.WriteAllBytes(remoteFile, originalContent);
  4710. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4711. {
  4712. s.Write(newContent, offset: 0, newContent.Length);
  4713. }
  4714. using (var downloaded = new MemoryStream())
  4715. {
  4716. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4717. downloaded.Position = 0;
  4718. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4719. }
  4720. }
  4721. finally
  4722. {
  4723. if (client.Exists(remoteFile))
  4724. {
  4725. client.DeleteFile(remoteFile);
  4726. }
  4727. }
  4728. }
  4729. }
  4730. [TestMethod]
  4731. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4732. {
  4733. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4734. {
  4735. client.Connect();
  4736. var remoteFile = GenerateUniqueRemoteFileName();
  4737. if (client.Exists(remoteFile))
  4738. {
  4739. client.DeleteFile(remoteFile);
  4740. }
  4741. try
  4742. {
  4743. Stream stream = null;
  4744. try
  4745. {
  4746. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4747. Assert.Fail();
  4748. }
  4749. catch (SshException)
  4750. {
  4751. }
  4752. finally
  4753. {
  4754. stream?.Dispose();
  4755. }
  4756. Assert.IsFalse(client.Exists(remoteFile));
  4757. }
  4758. finally
  4759. {
  4760. if (client.Exists(remoteFile))
  4761. {
  4762. client.DeleteFile(remoteFile);
  4763. }
  4764. }
  4765. }
  4766. }
  4767. [TestMethod]
  4768. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4769. {
  4770. // use new content that contains less bytes than original content to
  4771. // verify whether file is first truncated
  4772. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4773. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4774. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4775. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4776. {
  4777. client.Connect();
  4778. var remoteFile = GenerateUniqueRemoteFileName();
  4779. if (client.Exists(remoteFile))
  4780. {
  4781. client.DeleteFile(remoteFile);
  4782. }
  4783. try
  4784. {
  4785. client.WriteAllBytes(remoteFile, originalContent);
  4786. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4787. {
  4788. s.Write(newContent, offset: 0, newContent.Length);
  4789. }
  4790. using (var downloaded = new MemoryStream())
  4791. {
  4792. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4793. downloaded.Position = 0;
  4794. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4795. }
  4796. }
  4797. finally
  4798. {
  4799. if (client.Exists(remoteFile))
  4800. {
  4801. client.DeleteFile(remoteFile);
  4802. }
  4803. }
  4804. }
  4805. }
  4806. [TestMethod]
  4807. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4808. {
  4809. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4810. {
  4811. client.Connect();
  4812. var remoteFile = GenerateUniqueRemoteFileName();
  4813. if (client.Exists(remoteFile))
  4814. {
  4815. client.DeleteFile(remoteFile);
  4816. }
  4817. try
  4818. {
  4819. #region Verify if merely opening the file creates a zero-byte file
  4820. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4821. {
  4822. }
  4823. Assert.IsTrue(client.Exists(remoteFile));
  4824. var attributes = client.GetAttributes(remoteFile);
  4825. Assert.IsTrue(attributes.IsRegularFile);
  4826. Assert.AreEqual(0L, attributes.Size);
  4827. #endregion Verify if merely opening the file creates it
  4828. client.DeleteFile(remoteFile);
  4829. #region Verify if content is actually written to the file
  4830. var content = GenerateRandom(size: 100);
  4831. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4832. {
  4833. s.Write(content, offset: 0, content.Length);
  4834. }
  4835. using (var downloaded = new MemoryStream())
  4836. {
  4837. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4838. downloaded.Position = 0;
  4839. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4840. }
  4841. #endregion Verify if content is actually written to the file
  4842. }
  4843. finally
  4844. {
  4845. if (client.Exists(remoteFile))
  4846. {
  4847. client.DeleteFile(remoteFile);
  4848. }
  4849. }
  4850. }
  4851. }
  4852. [TestMethod]
  4853. public void Sftp_Open_Truncate_Write_ExistingFile()
  4854. {
  4855. const int fileSize = 5 * 1024;
  4856. // use new content that contains less bytes than original content to
  4857. // verify whether file is first truncated
  4858. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4859. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4860. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4861. using (var input = CreateMemoryStream(fileSize))
  4862. {
  4863. client.Connect();
  4864. var remoteFile = GenerateUniqueRemoteFileName();
  4865. if (client.Exists(remoteFile))
  4866. {
  4867. client.DeleteFile(remoteFile);
  4868. }
  4869. input.Position = 0;
  4870. try
  4871. {
  4872. client.WriteAllBytes(remoteFile, originalContent);
  4873. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4874. {
  4875. s.Write(newContent, offset: 0, newContent.Length);
  4876. }
  4877. using (var downloaded = new MemoryStream())
  4878. {
  4879. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4880. input.Position = 0;
  4881. downloaded.Position = 0;
  4882. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4883. }
  4884. }
  4885. finally
  4886. {
  4887. if (client.Exists(remoteFile))
  4888. {
  4889. client.DeleteFile(remoteFile);
  4890. }
  4891. }
  4892. }
  4893. }
  4894. [TestMethod]
  4895. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4896. {
  4897. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4898. {
  4899. client.Connect();
  4900. var remoteFile = GenerateUniqueRemoteFileName();
  4901. if (client.Exists(remoteFile))
  4902. {
  4903. client.DeleteFile(remoteFile);
  4904. }
  4905. try
  4906. {
  4907. Stream stream = null;
  4908. try
  4909. {
  4910. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4911. Assert.Fail();
  4912. }
  4913. catch (SshException)
  4914. {
  4915. }
  4916. Assert.IsFalse(client.Exists(remoteFile));
  4917. }
  4918. finally
  4919. {
  4920. if (client.Exists(remoteFile))
  4921. {
  4922. client.DeleteFile(remoteFile);
  4923. }
  4924. }
  4925. }
  4926. }
  4927. [TestMethod]
  4928. public void Sftp_SetLastAccessTime()
  4929. {
  4930. var testFilePath = "/home/sshnet/test-file.txt";
  4931. var testContent = "File";
  4932. using var client = new SftpClient(_connectionInfoFactory.Create());
  4933. client.Connect();
  4934. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4935. client.UploadFile(fileStream, testFilePath);
  4936. try
  4937. {
  4938. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4939. client.SetLastAccessTime(testFilePath, newTime);
  4940. var time = client.GetLastAccessTime(testFilePath);
  4941. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4942. }
  4943. finally
  4944. {
  4945. client.DeleteFile(testFilePath);
  4946. }
  4947. }
  4948. [TestMethod]
  4949. public void Sftp_SetLastAccessTimeUtc()
  4950. {
  4951. var testFilePath = "/home/sshnet/test-file.txt";
  4952. var testContent = "File";
  4953. using var client = new SftpClient(_connectionInfoFactory.Create());
  4954. client.Connect();
  4955. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4956. client.UploadFile(fileStream, testFilePath);
  4957. try
  4958. {
  4959. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  4960. client.SetLastAccessTimeUtc(testFilePath, newTime);
  4961. var time = client.GetLastAccessTimeUtc(testFilePath);
  4962. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4963. }
  4964. finally
  4965. {
  4966. client.DeleteFile(testFilePath);
  4967. }
  4968. }
  4969. [TestMethod]
  4970. public void Sftp_SetLastWriteTime()
  4971. {
  4972. var testFilePath = "/home/sshnet/test-file.txt";
  4973. var testContent = "File";
  4974. using var client = new SftpClient(_connectionInfoFactory.Create());
  4975. client.Connect();
  4976. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4977. client.UploadFile(fileStream, testFilePath);
  4978. try
  4979. {
  4980. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4981. client.SetLastWriteTime(testFilePath, newTime);
  4982. var time = client.GetLastWriteTime(testFilePath);
  4983. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4984. }
  4985. finally
  4986. {
  4987. client.DeleteFile(testFilePath);
  4988. }
  4989. }
  4990. [TestMethod]
  4991. public void Sftp_SetLastWriteTimeUtc()
  4992. {
  4993. var testFilePath = "/home/sshnet/test-file.txt";
  4994. var testContent = "File";
  4995. using var client = new SftpClient(_connectionInfoFactory.Create());
  4996. client.Connect();
  4997. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4998. client.UploadFile(fileStream, testFilePath);
  4999. try
  5000. {
  5001. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5002. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5003. var time = client.GetLastWriteTimeUtc(testFilePath);
  5004. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5005. }
  5006. finally
  5007. {
  5008. client.DeleteFile(testFilePath);
  5009. }
  5010. }
  5011. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5012. {
  5013. yield return new object[] { 0 };
  5014. yield return new object[] { 5 * 1024 * 1024 };
  5015. }
  5016. private static Encoding GetRandomEncoding()
  5017. {
  5018. var random = new Random().Next(1, 4);
  5019. switch (random)
  5020. {
  5021. case 1:
  5022. return Encoding.Unicode;
  5023. case 2:
  5024. return Encoding.UTF8;
  5025. default:
  5026. Debug.Assert(random == 3);
  5027. return Encoding.UTF32;
  5028. }
  5029. }
  5030. private void DownloadFileRandomMethod(SftpClient client, string path, Stream output)
  5031. {
  5032. Console.Write($"Downloading '{path}'");
  5033. var random = new Random().Next(1, 6);
  5034. switch (random)
  5035. {
  5036. case 1:
  5037. Console.WriteLine($" with {nameof(SftpClient.DownloadFile)}");
  5038. client.DownloadFile(path, output);
  5039. break;
  5040. case 2:
  5041. Console.WriteLine($" with {nameof(SftpClient.DownloadFileAsync)}");
  5042. client.DownloadFileAsync(path, output).GetAwaiter().GetResult();
  5043. break;
  5044. case 3:
  5045. Console.WriteLine($" with {nameof(SftpClient.BeginDownloadFile)}");
  5046. client.EndDownloadFile(client.BeginDownloadFile(path, output));
  5047. break;
  5048. case 4:
  5049. Console.WriteLine($" with {nameof(SftpFileStream.CopyTo)}");
  5050. using (var fs = client.OpenRead(path))
  5051. {
  5052. fs.CopyTo(output);
  5053. }
  5054. break;
  5055. default:
  5056. Debug.Assert(random == 5);
  5057. Console.WriteLine($" with {nameof(SftpFileStream.CopyToAsync)}");
  5058. using (var fs = client.OpenAsync(path, FileMode.Open, FileAccess.Read, CancellationToken.None).GetAwaiter().GetResult())
  5059. {
  5060. fs.CopyToAsync(output).GetAwaiter().GetResult();
  5061. }
  5062. break;
  5063. }
  5064. }
  5065. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5066. {
  5067. var preamble = encoding.GetPreamble();
  5068. var textBytes = encoding.GetBytes(text);
  5069. if (preamble.Length != 0)
  5070. {
  5071. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5072. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5073. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5074. return textAndPreambleBytes;
  5075. }
  5076. return textBytes;
  5077. }
  5078. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5079. {
  5080. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5081. }
  5082. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5083. {
  5084. var file = CreateTempFile(size);
  5085. try
  5086. {
  5087. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5088. {
  5089. client.UploadFile(fs, remoteFile);
  5090. }
  5091. }
  5092. finally
  5093. {
  5094. File.Delete(file);
  5095. }
  5096. }
  5097. private static byte[] GenerateRandom(int size)
  5098. {
  5099. var random = new Random();
  5100. var randomContent = new byte[size];
  5101. random.NextBytes(randomContent);
  5102. return randomContent;
  5103. }
  5104. private static Stream CreateStreamWithContent(string content)
  5105. {
  5106. var memoryStream = new MemoryStream();
  5107. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5108. sw.Write(content);
  5109. sw.Flush();
  5110. memoryStream.Position = 0;
  5111. return memoryStream;
  5112. }
  5113. private static string GenerateUniqueRemoteFileName()
  5114. {
  5115. return $"/home/sshnet/{Guid.NewGuid():D}";
  5116. }
  5117. }
  5118. }